I have a model named Tag
, with a ManyToManyField
named parents
:
parents = models.ManyToManyField('self', blank=True, symmetrical=False)
When I have a tag tag2
and try to add parent tag1
to it, Django seems to treat the relationship as symmetrical, when I need it to be asymmetrical. To be specific, when I run this code:
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())
This is the output:
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 []>
I need tag1
to be a parent of tag2
, but not vice versa. I'm able to make this happen through the admin interface, but I can't seem to do it in code. This seems like it should be a very basic and common function, so I'm confused as to why it's misbehaving.