此Django迁移错误消息是什么意思?

时间:2020-10-12 16:01:59

标签: django django-models

当我尝试为以下所示的Django模型创建迁移时,收到一条我不理解的错误消息。我正在尝试对可以将一个或多个其他成员添加为朋友或关注者的网站成员进行建模。另外,一个成员可以阻止任何其他成员。这是我的模特:

class Member(models.Model):
    FRIEND = "friend_of"
    FOLLOWS = "follows"
    RELATION_TYPES = ((FRIEND, "friend"), (FOLLOWS, "follower"))

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    relations = models.ManyToManyField(
        "self", choices=RELATION_TYPES, through="MemberRelation"
    )
    blocks = models.ManyToManyField("self", through="MemberBlock")

    def __str__(self):
        return self.user.first_name

class MemberRelation(models.Model):
    source = models.ForeignKey(
        "Member", related_name="source_member", on_delete=models.CASCADE
    )
    target = models.ForeignKey(
        "Member", related_name="target_member", on_delete=models.CASCADE
    )
    relation = models.CharField(max_length=8)  # Contains Member.FRIEND or .FOLLOWER

    def __str__(self):
        return "Member {} {} member {}".format(self.source, self.relation, self.target)

class MemberBlock(models.Model):
    source = models.ForeignKey(
        "Member", related_name="blocker", on_delete=models.CASCADE,
    )
    target = models.ForeignKey(
        "Member", related_name="blocked", on_delete=models.CASCADE,
    )

    def __str__(self):
        return "Member {} is blocking Member {}".format(self.source, self.target)

我从Member和MemberRelaton类开始,并且我的迁移运行没有任何错误。但是,在我的Member模型中添加了MemberBlock类和一个blocks ManyToMany字段之后,当我运行一个我不理解的makemigrations命令时,出现了以下错误:

  You are trying to change the nullable field 'source' on memberrelation to non-nullable 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...
  2) Ignore for now, and let me handle existing rows with NULL myself (e.g. because you added a RunPython or RunSQL operation to handle NULL values in a previous data migration)
  3) Quit, and let me add a default in models.py
  Select an option:

我不理解此错误,因为1)它是在谈论MemberRelation类,因为我已经添加了MemberBlock类。以前,此类没有问题。和2)错误是说'source'字段为空,我认为不是。

最初,我在没有blocks选项的情况下声明了through,并遇到了相同的错误。我添加了through选项,因为我认为在一个类中有两个递归的ManyToMany字段这一事实可能使Django感到困惑。

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

这是解决方案:

blocked = models.ManyToManyField("self", symmetrical=False, related_name="members")