Django:新的字段添加在执行makemigration时给出错误

时间:2018-03-28 15:42:17

标签: django django-models

我有博客的Post模型:

сlass Post(models.Model):
    author = models.ForeignKey(User,
                               related_name="blog_posts",
                               on_delete=models.CASCADE)
........
........

我想在项目中添加一个Tag,所以我制作了一个Tag模型:

class Tag(models.Model):
    tag_name = models.CharField(max_length=20,
                            blank=True)

    def __str__(self):
        return self.tag_name

我将此添加到Post模型中:

tag = models.ForeignKey(Tag, related_name="blog_tag",
                        on_delete=models.CASCADE)

但是makemigration给了我一个错误:

You are trying to add a non-nullable field 'tag' to post 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 with a null value for this column)
 2) Quit, and let me add a default in models.py

那为什么我必须填充现有的行?我怎么能把行空了? 附:如果我选择1)我仍然有错误。

1 个答案:

答案 0 :(得分:1)

您的数据库中已有数据,现在您在数据库表中添加了一个新列tag,该列也是not null

所以django说要么为先前存在的行提供一个默认数据,要么将这个新列(tag)设为空值(通过在字段的参数中添加null=True)以便现有的行将用null填充它。

相关问题