Django:如何添加递归不对称的多对多关系

时间:2017-11-16 05:29:18

标签: python django sqlite relational-database

我有一个名为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的父级,但反之亦然。我能够通过管理界面实现这一点,但我似乎无法在代码中执行此操作。这似乎应该是一个非常基本和常见的功能,所以我很困惑为什么它行为不端。

0 个答案:

没有答案