简体   繁体   中英

Django QuerySet select related objects

I have searched around but have not found a situation like mine. Assuming the use of Django's User Profile method to extend the default user features, how would a multi-object queryset get mapped a queryset of the related object.

For example (in the models):

class UserProfile(models.Model):
     user = models.OneToOneField(User, on_delete=models.CASCADE)

     friends = models.ManyToManyField("self", symmetrical=True, blank=True)

And inside the view:

class Friends(generics.ListAPIView):

    queryset=User.objects.all()
    serializer_class = UserSerializer

    def get_queryset(self):
        user = self.request.user
        profile = user.userprofile
        profiles = profile.friends.all()
        return profiles  #We want this to be a queryset of users

I have tried the following but this only works if profiles is of size one.

return User.objects.filter(userprofile=profiles)
 return User.objects.filter(userprofile__in=profiles)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM