我有一个名为Tag
的模型,ManyToManyField
名为parents
:
parents = models.ManyToManyField('self', blank=True, symmetrical=False)
当我有一个标签tag2
并尝试向其添加父tag1
时,Django似乎将这种关系视为对称,当我需要它不对称时。具体来说,当我运行此代码时:
tag1 = Tag.objects.get(name='Academic')
tag2 = Tag.objects.get(name='Accounting')
tag1.parents.clear()
tag2.parents.clear()
print("Before:")
print("Tag1 has these parents:", tag1.parents.all())
print("Tag2 has these parents:", tag2.parents.all())
tag2.parents.add(tag1)
print("After:")
print("Tag1 has these parents:", tag1.parents.all())
print("Tag2 has these parents:", tag2.parents.all())
tag1.parents.clear()
print("Lastly:")
print("Tag1 has these parents:", tag1.parents.all())
print("Tag2 has these parents:", tag2.parents.all())
这是输出:
After first clearing:
Tag1 has these parents: <QuerySet []>
Tag2 has these parents: <QuerySet []>
After adding parent:
Tag1 has these parents: <QuerySet [<Tag: Accounting>]>
Tag2 has these parents: <QuerySet [<Tag: Academic>]>
After clearing again:
Tag1 has these parents: <QuerySet []>
Tag2 has these parents: <QuerySet []>
我需要tag1
成为tag2
的父级,但反之亦然。我能够通过管理界面实现这一点,但我似乎无法在代码中执行此操作。这似乎应该是一个非常基本和常见的功能,所以我很困惑为什么它行为不端。