4
使用Django的新移民的框架,让我们说我有一个已经存在于数据库中的以下模型:的Django 1.7空白CharField /文本字段约定
class TestModel(models.Model):
field_1 = models.CharField(max_length=20)
我现在想要一个新的文本字段添加到模型,所以它看起来像这样:
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
我可以很容易地通过增加null=True
到field_2
解决这个问题,但Django的惯例是避免像CharField和TextField(从https://docs.djangoproject.com/en/dev/ref/models/fields/)基于字符串的字段中使用空。这是一个错误,还是我误解了文档?
我想这是有道理的,但它令我奇怪的行为。我期望如果我指定'blank = True',迁移将自动使用一个空字符串作为默认值,与我指定'null = True'相同的方式,我不需要告诉迁移使用'NULL '作为默认值。 – 2014-11-03 17:18:29
好吧,'显式优于隐式'。 'blank = True'只告诉django管理员接受空字符串作为输入,它并不意味着默认值。 'default ='确实如此,并且指定与空字符串不同的默认值是非常合理的。对于'null = True',迁移并不使用'NULL'作为默认值,而只是没有 - 这恰好“评估”为NULL。 – ch3ka 2014-11-03 17:22:10