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

Time:09-03

I would like to get a list of UserProfile of a user's followers

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.

CodePudding user response:

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)

CodePudding user response:

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