gpt4 book ai didi

python - 将一列添加到表 django

转载 作者:行者123 更新时间:2023-12-03 21:34:52 26 4
gpt4 key购买 nike

我想在 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 个选项并删除了以前的迁移。然后运行 ​​ makemigrationsmigrations ,只是为了避免重写默认值。这就是我收到错误的原因。

但是,当我选择第二个选项然后给出默认值时,我运行上面的命令,它起作用了。
问题是我只是想避免提供默认值。我不知道为什么在添加额外的字段时它是必需的,但是在创建一个字段时,它不是必需的。

最佳答案

这就是我每次做的Django似乎不允许我更改表格。重命名 model ,对 Student_1 说.然后添加新字段:

class Student_1(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 .

关于python - 将一列添加到表 django,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37251024/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com