【发布时间】: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