【问题标题】:Is it possible to add parent to child for ForeignKey relationship?是否可以为 ForeignKey 关系添加父级到子级?
【发布时间】:2021-01-06 02:09:52
【问题描述】:

假设我有一个名为“parent”的 ForeignKey 字段,其相关名称为“children”:

class Item(PolymorphicModel):
    title = models.CharField()
    parent = models.ForeignKey(
        "self", related_name='children', null=True, blank=True, on_delete=models.CASCADE)

class Parent(Item):
    pass

class Child(Item):
    pass

为什么我只能将子添加到父级,但如果我尝试将父级添加到子级,则会出现错误?

所以这行得通:

p1 = Parent.objects.create(title="Parent 1")
c1 = Child.objects.create(title="Child 1")

print(p1.children)
#<PolymorphicQuerySet []>

p1.children.add(c1)

但这不是:

p1 = Parent.objects.create(title="Parent 1")
c1 = Child.objects.create(title="Child 1")
print(c1.parent)
# None

c1.parent.add(p1)
# AttributeError: 'NoneType' object has no attribute 'add'

我是否只需要每次都添加到 Parent 的 children 字段?有没有办法添加到孩子的父母呢?是否有任何理由为什么添加到孩子的父母不起作用或不应该使用?

对于在这种情况下何时/如何使用“_set”(如果相关),我也有点困惑。所以按照Django's Many-to-one example的格式,下面的对我也不起作用:

p1 = Parent.objects.create(title="Parent 1")
c1 = Child.objects.create(title="Child 1")
p1.children.add(c1)

print(p1.children_set.all())
# AttributeError: 'p1' object has no attribute 'children_set'

print(c1.parent_set.all())
# AttributeError: 'c1' object has no attribute 'parent_set'

print(p1.item_set.all())
# AttributeError: 'p1' object has no attribute 'item_set'

【问题讨论】:

    标签: django django-models django-polymorphic


    【解决方案1】:

    所以我认为您在这里与 parentchild 命名混淆了。 ForeignKey 中的 related_name 字段本质上是告诉模型建立关系以快速找到具有给定 ForeignKey 的模型的所有相关实例。当您调用p1.children 时,您将获得正确的输出,因为没有与p1 相关的实例。当您调用c1.parent 并获得None 时,您同样会获得正确的输出。我在下面复制并粘贴的行是导致这种情况的原因。通过设置null=True,您就是说要实例化Item 实例(无论是Parent 还是Child),并带有一个空的parent 字段(在python 中,空是None)。

    当您致电c1.parent.add() 时,您就会发现问题。由于您没有将parent 设置为任何值,因此它的值为None,并且它同样没有add() 方法。你应该做的是设置parent=[some instance of Parent]。然后,当您想获取给定Parent 实例的children 时,假设p1,您可以调用p1.children,您将获得一个充满Child 实例的查询集,其parent 字段具有已设置为该 Parent 实例的外键。

    parent = models.ForeignKey(
        "self", related_name='children', null=True, blank=True, on_delete=models.CASCADE)
    

    【讨论】:

      猜你喜欢
      • 2020-03-21
      • 2013-05-03
      • 1970-01-01
      • 2018-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多