简体   繁体   English

Django 1.7空白CharField / TextField约定

[英]Django 1.7 blank CharField/TextField convention

Using Django's new migration framework, let's say I have the following model that already exists in the database: 使用Django的新迁移框架,假设我具有数据库中已经存在的以下模型:

class TestModel(models.Model):
    field_1 = models.CharField(max_length=20)

I now want to add a new TextField to the model, so it looks like this: 我现在想向模型中添加一个新的TextField,所以它看起来像这样:

class TestModel(models.Model):
    field_1 = models.CharField(max_length=20)
    field_2 = models.TextField(blank=True)

When I try to migrate this model using python manage.py makemigrations , I get this prompt: 当我尝试使用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

I can easily fix this by adding null=True to field_2 , but Django's convention is to avoid using null on string-based fields like CharField and TextField (from https://docs.djangoproject.com/en/dev/ref/models/fields/ ). 我可以通过在field_2添加null=True来轻松解决此field_2 ,但是Django的约定是避免在基于字符串的字段(例如CharField和TextField)上使用null(来自https://docs.djangoproject.com/zh-CN/dev/ref/models/字段/ )。 Is this a bug, or am I misunderstanding the docs? 这是一个错误,还是我误解了文档?

It's not a bug, it's documented and logical. 这不是错误,而是经过记录和合乎逻辑的。 You add a new field, which is (by best practice, as you noticed) not NULL able so django has to put something into it for the existing records - I guess you want it to be the empty string. 您添加了一个新字段,该字段(按照最佳实践,如您所注意到的那样)不能为NULL因此django必须为现有记录添加一些内容-我想您希望它为空字符串。

you can 您可以

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

so just press 1, and provide '' (the empty string) as value. 因此只需按1,然后提供'' (空字符串)作为值。

or specify default='' in the models.py, as suggested: 或根据建议在models.py中指定default=''

 2) Quit, and let me add a default in models.py
  1. select 1 ,it will through to python terminal. 选择1,它将通过python终端。
  2. Give timezone.now(), it will exit from python terminal. 给定timezone.now(),它将从python终端退出。

Note:it may not exit from terminal at first time,give that command once again. 注意:它可能不会在第一时间从终端退出,请再次给出该命令。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM