Python 您正在尝试在没有默认值的情况下向 contact_info 添加不可为空的字段“id”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32991965/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
You are trying to add a non-nullable field 'id' to contact_info without a default
提问by shashank
i am just using simple command python manage.py makemigrations
我只是使用简单的命令 python manage.py makemigrations
However, all I get is this error:
但是,我得到的只是这个错误:
You are trying to add a non-nullable field 'id' to contact_info 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
Here is models.py:
这是models.py:
class Document(models.Model):
docfile = models.FileField(upload_to='documents/')
class contact_number(models.Model):
contact_numbers= models.CharField(max_length=13)
class contact_address(models.Model):
address = models.CharField(max_length=100)
city = models.CharField(max_length=50)
state = models.CharField(max_length=50)
zip = models.CharField(max_length=5)
class contact_info(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField()
contact_numbers=models.ManyToManyField(contact_number)
addresses=models.ManyToManyField(contact_address)
采纳答案by pycod333
you could set `default="" and also editable=False.
你可以设置`default="" 和editable=False。
E.g first_name = models.CharField(max_length=50, default="", editable=False)
.
例如first_name = models.CharField(max_length=50, default="", editable=False)
。
Adding id field is unnecessary. Django will add it automatically.
添加 id 字段是不必要的。Django 会自动添加它。
Edit: Deleting the last migration files in your migrations folder and retry again. If it doesn't work, repeat the same process, you will know you have deleted the right file when your "makemigrations" command works.
编辑:删除迁移文件夹中的最后一个迁移文件,然后重试。如果它不起作用,请重复相同的过程,当您的“makemigrations”命令起作用时,您将知道您删除了正确的文件。
回答by Jan Skácel
This is happening because you have non-empty database. There must be line which has not been created through Django ORM.
发生这种情况是因为您有非空数据库。必须有未通过 Django ORM 创建的行。
Do the following: python manage.py shell
执行以下操作: python manage.py shell
from <path_to_your_models> import *
print len(list(contact_info.objects.filter(id = None)))
This way you find out how many such rows are there. If you want to keep them just make migration script with some value that you give it to it.
通过这种方式,您可以找出有多少这样的行。如果您想保留它们,只需使用您赋予它的某些值来制作迁移脚本。
回答by Anil Kumar Gupta
You need to set a default value. For example:
您需要设置一个默认值。例如:
field_eg = models.CharField(default="")
means:
方法:
name = models.CharField(max_length=100, default="")
回答by mehmet
This happens when a different field was marked as primary key with primary_key=True
earlier and you are removing that (in case of which django tries to add an id
primary key).
当一个不同的字段被标记为主键时会发生这种情况,primary_key=True
并且您正在删除它(以防 django 尝试添加id
主键)。
That Django is asking for a default value for a primary key seems to be a bug.
Django 要求主键的默认值似乎是一个错误。
To work around this problem, follow these steps:
要变通解决此问题,请按照下列步骤操作:
Supply a random default value when prompted during makemigrations.
Go to the migration file generated (under
your_app\migrations\
and delete thedefault=x,
, x being the random value you supplied in step 1.While you are at the migration file, make sure the order of actions make sense (e.g., remove/alter one primary key before adding another). Save and close.
Migrate as usual.
在 makemigration 期间提示时提供随机默认值。
转到生成的迁移文件(在
your_app\migrations\
并删除default=x,
, x 是您在步骤 1 中提供的随机值。当您在迁移文件中时,请确保操作的顺序有意义(例如,在添加另一个主键之前删除/更改一个主键)。保存并关闭。
像往常一样迁移。
回答by Afiz
I ran into similar problem when doing makemigration. I had primary key with name 'Identity' and other fields in my models to which I applied makemigrations. Later, I changed primary key name to '_id' and I got this error.
我在做 makemigration 时遇到了类似的问题。我在应用 makemigrations 的模型中有名为“Identity”的主键和其他字段。后来,我将主键名称更改为 '_id' 并出现此错误。
You are trying to add a non-nullable field '_id' to swapidentity without a default; we can't do that (the database needs something to populate existing rows).
您正在尝试在没有默认值的情况下将不可为空的字段“_id”添加到 swapidentity;我们不能这样做(数据库需要一些东西来填充现有的行)。
Error is bit misleading, but if you change back '_id' to 'Identity' you will not get that error.
错误有点误导,但如果您将 '_id' 改回 'Identity',您将不会收到该错误。
How to fix? Delete migration script generated under migrations package. Or manually change primary key in your generated migration script.
怎么修?删除迁移包下生成的迁移脚本。或者在生成的迁移脚本中手动更改主键。
回答by Chandan
This can also happen if you made some changes in your models.py and tried migrating afterwards. Happened to me once. Deleting the entire database didn't help after all. In case the error is arriving after adding a Foreign Key, you cannot provide a default or it might be unsafe to set default as null.
如果您对 models.py 进行了一些更改,然后尝试迁移,也会发生这种情况。发生在我身上一次。毕竟删除整个数据库没有帮助。如果添加外键后出现错误,则不能提供默认值,否则将默认值设置为 null 可能不安全。
Probably Django still has some of the previous migrations files in your myapp/migrations/ folder. Deleting those files might help.
可能 Django 在您的 myapp/migrations/ 文件夹中仍有一些以前的迁移文件。删除这些文件可能会有所帮助。
回答by Dash2TheDot
In my opinion, completely deleting the migrations is a lazy and bad idea. I did a snafu similar to @Afiz Momin and was able to dig myself out.
在我看来,完全删除迁移是一个懒惰和坏主意。我做了一个类似于@Afiz Momin 的混乱,并且能够把自己挖出来。
I had the following setup:
我有以下设置:
- A base abstractmodel.
- Override the
id
field after creation (bad idea) - All other subclasses triggered Django migrations to try to create the ID field from the parent class.
- 一个基本的抽象模型。
id
创建后覆盖该字段(坏主意)- 所有其他子类都会触发 Django 迁移以尝试从父类创建 ID 字段。
So I would get the following every single timeI ran makemigrations
:
所以我每次跑步都会得到以下信息makemigrations
:
You are trying to add a non-nullable field 'id' to <tablename> 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 with a null value for this column)
2) Quit, and let me add a default in models.py
But there was a way out.
但是有出路。
In my first attempt I would just seed a fake value in and then delete the created id
column, but this was obviously unsustainable. But on a whim I did the following:
在我的第一次尝试中,我只是在其中播种了一个假值,然后删除了创建的id
列,但这显然是不可持续的。但一时兴起,我做了以下事情:
- Backup the migrations directory to
migrations.orig
. - Run
./manage.py makemigrations
to make all migrations. - Inspect the newly-created migrations file
0001-initial
.
- 将迁移目录备份到
migrations.orig
. - 运行
./manage.py makemigrations
以进行所有迁移。 - 检查新创建的迁移文件
0001-initial
。
Chances are the model it's complaining about (<tablename>
) is missing vital info. For me, it was missing the bases
argument:
很有可能它抱怨的模型 ( <tablename>
) 缺少重要信息。对我来说,它缺少bases
论点:
migrations.CreateModel(
name='<ModelName>',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('some_field', models.IntegerField()),
# ... other fields ...
],
options={
'abstract': False,
},
bases=(<base_classes>),
),
- Now go back to
migrations.orig
and search for the the migration where the model is first created. The migration line will look similar to the one above. - Once you find the line in
migrations.orig
, modify it to match the new migration code. - Restore your original migrations. Delete
migrations
and renamemigrations.orig
tomigrations
. - Just for good measure, run
./manage.py makemigrations
and./manage.py migrate
. You should get no error messages anymore! - If it complains about another model, follow the same procedure described.
- 现在返回
migrations.orig
并搜索首次创建模型的迁移。迁移线看起来与上面的类似。 - 在 中找到该行后
migrations.orig
,修改它以匹配新的迁移代码。 - 恢复您的原始迁移。删除
migrations
并重命名migrations.orig
为migrations
. - 只是为了更好的衡量,运行
./manage.py makemigrations
和./manage.py migrate
。您应该不会再收到错误消息了! - 如果它抱怨其他型号,请按照所描述的相同程序进行操作。
回答by sarath kumar
Check Your Migration Files
检查您的迁移文件
./manage.py showmigrations <App Name>
./manage.py showmigrations <App Name>
[X] 0001_initial
[X] 0001_initial
[X] 0002_auto_20181204_1110
[X] 0002_auto_20181204_1110
Revert Your Migrations Using
使用恢复您的迁移
./manage.py migrate <App Name> <migration file name>
eg: 0001_initial
./manage.py migrate <App Name> <migration file name>
例如:0001_initial
or use zero (for complete migration revert) ./manage.py migrate <App Name> zero
或使用零(用于完全迁移还原) ./manage.py migrate <App Name> zero
Check Your Migrations
检查您的迁移
./manage.py showmigrations <App Name>
./manage.py showmigrations <App Name>
[ ] 0001_initial
[ ] 0001_initial
[ ] 0002_auto_20181204_1110
[ ] 0002_auto_20181204_1110
Now delete all revert migrations and migrate again.
现在删除所有还原迁移并再次迁移。
./manage.py migrate <App Name>
./manage.py migrate <App Name>
回答by Sundaram Seth
The database needs something to populate existing rows. So here you want to define some value for it you can use default=""
数据库需要一些东西来填充现有的行。所以在这里你想为它定义一些值,你可以使用 default=""
contact_info = models.CharField(default="" ,max_length=15)