我想在django中为模型添加一列。我使用的数据库是mysql。 早期的数据库文件是;
class Student(models.Model):
name = models.CharField(max_length=20, validators=[validate_name])
password = models.CharField(max_length=100)
email = models.EmailField(max_length=50)
class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = '__all__'
现在,我在密码后添加了以下行:
repeat_password = models.CharField(max_length=100)
现在我正在运行以下命令:
python manage.py makemigrations
python manage.py migrate
第一行产生0001_initial.py
,其内容为:
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Student',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=20, validators=[ajax.models.validate_name])),
('password', models.CharField(max_length=100)),
('repeat_password', models.CharField(max_length=100)),
('email', models.EmailField(max_length=50)),
],
),
]
但是,第二行不会向数据库添加任何内容:
mysql> desc ajax_student;
+----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(20) | NO | | NULL | |
| password | varchar(100) | NO | | NULL | |
| email | varchar(10) | NO | | NULL | |
+----------+--------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
我不知道我做错了什么? 我在SO上寻找答案,但没有一个有效:Altering database tables in Django
Adding fields to an already existing database
请帮我解决这个问题。
修改
感谢您的帮助。当我添加字段repeat_password
时,它要求默认值:
You are trying to add a non-nullable field 'repeat_password' to student without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows)
2) Quit, and let me add a default in models.py
Select an option: 1
Please enter the default value now, as valid Python
The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now()
所以,我做错了是选择了1个选项并删除了以前的迁移。然后,运行makemigrations
和migrations
,以避免重写默认值。这就是我收到错误的原因。
但是,当我选择第二个选项然后给出一个默认值时,我运行上面的命令,它工作。 问题是我只想避免提供默认值。我不知道为什么在添加额外字段时需要它,但在创建字段时,不需要它。
答案 0 :(得分:0)
这是我在Django
似乎不允许我更改表时所做的事情。重命名model
,例如说Student_1
。然后添加新字段:
class Student(models.Model):
name = models.CharField(max_length=20, validators=[validate_name])
password = models.CharField(max_length=100)
email = models.EmailField(max_length=50)
repeat_password = models.CharField(max_length=100)
运行python manage.py makemigrations
,它将识别新表student_1
。然后运行python manage.py migrate
。
答案 1 :(得分:0)
我绝对尝试了所有方法,但@Gathide 的答案确实是唯一有效的方法。
将您的 model
重命名为 Student1
,然后应用通常的:
python manage.py makemigrations
python manage.py migrate
很有魅力。只需确保将views.py、forms.py 和admin.py 中所有以前的Student
模型更新为Student1