【问题标题】:Django models ForeignKeyDjango 模型 ForeignKey
【发布时间】:2015-02-18 15:38:03
【问题描述】:

这是数据库模型的django1.7代码 我对这段代码有疑问。 这是models.py文件。

class Person(models.Model):
    person_id=models.AutoField(primary_key=True)
    person_name=models.CharField(max_length=100)
    person_family=models.CharField(max_length=100)
    person_father=models.ForeignKey('Person')
    person_mother=models.ForeignKey('Person')

错误:

如果我删除其中一个 -> 'person_mother 或 person_father' 错误将消失。 但是当它们都在代码中时会发生错误!

【问题讨论】:

    标签: django django-1.7


    【解决方案1】:

    请阅读您在运行 migrate(或尝试运行 validate)时收到的提示:您需要将 related_name kwarg 添加到您的 ForeignKey,如下所示:

    person_father=models.ForeignKey('Person', related_name='child_from_father') person_mother=models.ForeignKey('Person', related_name='child_from_mother')

    您需要使用related_name,因为当Django 遇到ForeignKey 时,它会尝试在外键模型中添加一个反向关系 字段。例如,如果你有一个Author 模型和一个Book 模型,它有一个ForeignKeyAuthor,django 将添加一个book_set 反向关系管理器属性到Author(以查询所有Books特定的Author)。

    现在,在您的情况下,Django 想要将 person_set 添加到 Person,但是,因为您有两个 ForeignKeysPerson,它不知道如何命名反向关系管理器属性。这就是为什么它提示您使用related_name。因此,使用person_father 属性将为您提供一个人父亲的查询集,而person_mother 则为母亲提供相同的查询集。

    【讨论】:

    • 您的相关名称相当混乱。这些相关的名字代表“孩子”,所以可能是“child_from_father”和“child_from_mother”
    • 另外,您使用的是字段的确切名称。那不应该通过模型检查
    • @Alvaro 可能你是对的......我已经改变了它们
    • 同意 - 大多数时候我喜欢为字段名称和相关名称使用相同的名称。但是,这在这种情况下不起作用(因为 ForeignKey 是 same 模型)
    • 不错!另一个问题:您从哪里获得有关 django 的确切知识?我的意思是这样的问题!?
    猜你喜欢
    • 2019-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-29
    • 1970-01-01
    • 2011-08-21
    • 2020-01-19
    相关资源
    最近更新 更多