[英]Django 1.7 blank CharField/TextField convention
使用Django的新迁移框架,假设我具有数据库中已经存在的以下模型:
class TestModel(models.Model):
field_1 = models.CharField(max_length=20)
我现在想向模型中添加一个新的TextField,所以它看起来像这样:
class TestModel(models.Model):
field_1 = models.CharField(max_length=20)
field_2 = models.TextField(blank=True)
当我尝试使用python manage.py makemigrations
迁移此模型时,出现以下提示:
You are trying to add a non-nullable field 'field_2' to testmodel 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
我可以通过在field_2
添加null=True
来轻松解决此field_2
,但是Django的约定是避免在基于字符串的字段(例如CharField和TextField)上使用null(来自https://docs.djangoproject.com/zh-CN/dev/ref/models/字段/ )。 这是一个错误,还是我误解了文档?
这不是错误,而是经过记录和合乎逻辑的。 您添加了一个新字段,该字段(按照最佳实践,如您所注意到的那样)不能为NULL
因此django必须为现有记录添加一些内容-我想您希望它为空字符串。
您可以
1) Provide a one-off default now (will be set on all existing rows)
因此只需按1,然后提供''
(空字符串)作为值。
或根据建议在models.py中指定default=''
:
2) Quit, and let me add a default in models.py
注意:它可能不会在第一时间从终端退出,请再次给出该命令。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.