Home > Blockchain >  Django application doesn't seem to recognize related name?
Django application doesn't seem to recognize related name?

Time:03-23

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'

CodePudding user response:

According to documentation all many to many relationships that are recursive are also symmetrical by default.

See here: https://docs.djangoproject.com/en/4.0/ref/models/fields/#django.db.models.ManyToManyField.symmetrical

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)
  • Related