Bigair
Bigair

Reputation: 1592

How to return list of one-to-one relation objects

I have a model named Profile which is OneToOne related to User model. Profile has ManyToMany Field named muting_users.

I need to return list of muting_users from API View show below but I only managed to return list of Profiles.

How can I return list of users in listed case(code below)?

class Profile(models.Model):

    user = models.OneToOneField(User, on_delete = models.CASCADE)
    muting_users = models.ManyToManyField('self', blank = True, related_name = 'muted_by', symmetrical = False)

class MutingUserListAPIView(generics.ListAPIView):

    serializer_class = serializers.UserSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        request_user = self.request.user
        return request_user.profile.muting_users.all() # < it returning list of Profile but should return list of Users

Upvotes: 0

Views: 89

Answers (2)

Jerven Clark
Jerven Clark

Reputation: 1219

You can filter the users using the relationship like so:

def get_queryset(self):
    request_user = self.request.user
    return User.objects.filter(profile__in=request_user.profile.muting_users.all())

This way, you can get the data from the db in two goes which will return a queryset so you can chain other functions like count, or further filters, etc.

Upvotes: 1

dani herrera
dani herrera

Reputation: 51665

You can get the user for each muted profile:

def get_queryset(self):
    request_user = self.request.user
    muted_profiles = request_user.profile.muting_users.all()
    muted_users = [profile.user for profile in muted_profiles] # (*1)
    return muted_users

(*1) Be free to optimize code to avoid a db request for each profile:

muted_profiles = (
    request_user
   .profile
   .muting_users
   .select_related('user') # <-- this
   .all()   
)

Upvotes: 0

Related Questions