「children」の related_name を持つ「parent」という名前の ForeignKey フィールドがあるとします。
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'
毎回親の子フィールドに追加する必要がありますか? 代わりに子の親に追加する方法はありませんか? 子の親への追加が機能しない、または使用すべきではない理由はありますか?
また、この状況で「_set」をいつ/どのように使用するかについても少し混乱しています(関連する場合)。したがって、Django の 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'