Search code examples
djangomanytomanyfield

Django - How to properly access reverse relationship ManyToManyField


This is my models.py (I'm using the default Django User model as well):

class UserExtended(models.Model):
    user = models.OneToOneField(User, related_name="userextended_set")
    location = models.ForeignKey(Location)
    follow = models.ManyToManyField(User, related_name="follow_set")

Now, to access a list of 'follow' users of a particular user (users which a particular user is following), I'd do something like this:

a = User.objects.get(username='a')
a.userextended_set.follow.count()

My question is, how do I get a list of users whom a particular user is on the 'follow' list of (i.e. who are following him)? I tried this:

# Assuming user 'a' is on the 'follow' list of only one users (i.e.
# assuming .get() will only return one user object).
User.objects.get(username='a').follow_set.get().username

but I get an error saying

AttributeError: 'UserExtended' object has no attribute 'username'

Solution

  • I think this could be what you need:

    user  # this is your user
    UserExtended.objects.filter(follow=user)