I have this model:
class Person(models.Model):
something ...
employers = models.ManyToManyField(\'self\', blank=True, related_name=\'employees\')
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()