Django related_name not found
django, orm, python
Solution
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()
Problem
I have this model: ``` class Person(models.Model): something ... employers = models.ManyToManyField('self', blank=True, related_name='employees') ``` When I do `person.employees.all()` I get this error: `'Person' object has no attribute 'employees'`. Is the related name only created when there is an actual link in place. If yes, how can I check this? EDIT: I'm aware of the `hasattr()` function. I'm still wondering why the attribute doesn't return an empty list when there's no related objects.