Skip to content Skip to sidebar Skip to footer

Django Related_name Not Found

I have this model: class Person(models.Model): something ... employers = models.ManyToManyField('self', blank=True, related_name='employees') When I do person.employees.al

Solution 1:

To use related_name with recursive many-to-many you need set symmetrical=False. Without it Django will not add employees attribute to the class. From the docs:

When Django processes this model, it identifies that it has a ManyToManyField on itself, and as a result, it doesn’t add a person_set attribute to the Person class. Instead, the ManyToManyField is assumed to be symmetrical – that is, if I am your friend, then you are my friend.

So you can add symmetrical=False to the field:

employers = models.ManyToManyField('self', blank=True, related_name='employees', symmetrical=False)

person.employees.all() # will work now

or just use employers attribute:

person.employers.all()

Post a Comment for "Django Related_name Not Found"