How to get a list of objects using several model relationships in Django?

I want to get the list of UserProfile of a user's followers from a username

I have the following models :

class User(AbstractBaseUser, PermissionsMixin):
    username = models.CharField(max_length=16, unique=True, db_index=True)
#   ...

class UserProfile(models.Model):
    user = models.OneToOneField(User, related_name="profile", on_delete=models.CASCADE)
#   ...

class UserFollow(models.Model):
    follower = models.ForeignKey(User, related_name="follow_follower", on_delete=models.CASCADE)
    following = models.ForeignKey(User, related_name="follow_following", on_delete=models.CASCADE)
    date_created = models.DateTimeField(auto_now_add=True, editable=False)
#   ...

How can I accomplish this while optimizing database queries ?

I use rest framework.

If I understand correctly, given a username of a user (say user1), you want to retrieve all the userprofiles from the users following user1, right?

Whereas I do not think this is possible with a one-liner, I think the following should to the trick:

followers = UserFollow.objects.filter(following__username=username).values('follower')
follower_profiles = UserProfile.objects.filter(user__in=followers)

I saw your message, you want : follower_profiles = User.objects.get(username=username).follow_following.all().follower.profile

You should want this.

User.objects.get(username='username').follow_follower.select_related('follower__profile').all().follower.profile
Back to Top