13

使用 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我可以通过添加to轻松解决此问题field_2,但 Django 的约定是避免在基于字符串的字段上使用 null,例如 CharField 和 TextField(来自https://docs.djangoproject.com/en/dev/ref/models/fields/)。这是一个错误,还是我误解了文档?

4

2 回答 2

38

这不是错误,它已记录在案且符合逻辑。您添加了一个新字段,该字段(通过最佳实践,正如您所注意到的)不能NULL,因此 django 必须为现有记录添加一些内容 - 我猜您希望它是空字符串。

你可以

 1) Provide a one-off default now (will be set on all existing rows)

所以只需按 1,并提供''(空字符串)作为值。

default=''按照建议在models.py中指定:

 2) Quit, and let me add a default in models.py
于 2014-11-03T17:04:37.807 回答
1
  1. 选择 1 ,它将通过 python 终端。
  2. 给 timezone.now(),它将从 python 终端退出。

注意:它可能不会在第一次退出终端,再次给出该命令。

于 2019-05-16T18:52:29.880 回答