'Django application doesn't seem to recognize related name?
I have a django app with a User's model that contains a followers field that serves the purpose of containing who follows the user and by using related_name we can get who the User follows. Vice versa type of thing. Printing the User's followers works, but I can't seem to get the followees to work.
views.py
followers = User.objects.get(username='bellfrank2').followers.all()
following = User.objects.get(username='bellfrank2').followees.all()
print(followers)
print(following)
models.py
class User(AbstractUser):
followers = models.ManyToManyField('self', blank=True, related_name="followees")
Error:
AttributeError: 'User' object has no attribute 'followees'
Solution 1:[1]
According to documentation all many to many relationships that are recursive are also symmetrical by default.
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 to, make your field actually create the followees attribute you need to set the symmetrical attribute to False.
models.py
class User(AbstractUser):
followers = models.ManyToManyField('self', blank=True, related_name="followees", symmetrical=False)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
