Issue
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
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)
Answered By - vinkomlacic
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.