Django数据库操作中You are trying to add a non-nullable field 'name' to contact without a default错误处理

name = models.CharField(max_length=50)
执行:python manage.py makemirations出现以下错误:


You are trying to add a non-nullable field 'name' to contact 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
Select an option: 

原因:因为新增加了一个字段,而在此之前的数据,肯定是没有值的,但这个字段不能为空,所以需要一个默认值。或者也可以把这个字段允许为空。


解决方法:
先给'name'任意初始值:name = models.CharField(max_length=50, default='')
然后执行:python manage.py makemirations
再执行:python manage.py migrate


再将default删去,即执行:name = models.CharField(max_length=50)
执行:python manage.py makemirations
再执行:python manage.py migrate


解决!



注意:在开发过程中,数据库同步误操作之后,难免会遇到后面不能同步成功的情况,解决这个问题的一个简单粗暴方法是把migrations目录下的脚本(除__init__.py之外)全部删掉,再把数据库删掉之后创建一个新的数据库,数据库同步操作再重新做一遍。 

猜你喜欢

转载自www.cnblogs.com/aaron-agu/p/8985055.html
今日推荐