首页 文章

Django 1.7空白CharField / TextField约定

提问于
浏览
5

使用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

我可以通过将 null=True 添加到 field_2 来轻松解决此问题,但Django的惯例是避免在基于字符串的字段(如CharField和TextField(来自https://docs.djangoproject.com/en/dev/ref/models/fields/))上使用null . 这是一个错误,还是我误解了文档?

1 回答

  • 22

    它's not a bug, it' s记录和逻辑 . 你添加一个新的字段,这是(通过最佳实践,你注意到的)不是 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
    

相关问题