How to return a queryset of friend requests in DRF ListAPIView?

911 Views Asked by At

I am using this django app in my django rest framework(DRF) backend api to manage bi-directional friendships between users of my android app. In one of my DRF views I want to return a queryset of all a user's unread friend requests. In the django-friendship docs it says that to

List all unread friendship requests:

Friend.objects.unread_requests(user=request.user)

Here is my ListAPIView:

class ListUnseenFriendRequests(generics.ListAPIView):
    serializer_class = serializers.FriendRequestSerializer
    permission_classes = (IsAuthenticated,)

    def get_queryset(self):
        return Friend.objects.unread_requests(user=self.request.user)

The serializer FriendRequestSerializer looks like this:

class FriendRequestSerializer(serializers.Serializer):
    from_user = models.ForeignKey(User, related_name='friendship_requests_sent')
    to_user = models.ForeignKey(User, related_name='friendship_requests_received')
    created = models.DateTimeField(default=timezone.now)

I use the same field names in the serializer as the FriendshipRequest model in the django-friendship source code.

When I run the server and make an api request to the corresponding endpoint /friendship/list-unseen-friend-requests/, the JSON response is the following:

[
    {},
    {},
    {}
]

I had sent 3 friend requests to this user so the number is correct however they are all null.

How do I fix this such that the friend requests are returned none null?

I have tried changing the serializer to a ModelSerializer like so:

class FriendRequestSerializer(serializers.ModelSerializer):
    class Meta:
        model = FriendshipRequest
        fields = ('from_user', 'to_user', 'created')

The result is the following when the api endpoint is called:

AttributeError: 'tuple' object has no attribute 'values'
[31/Jul/2017 08:26:32] "GET /friendship/list-unseen-friend-requests/ HTTP/1.1" 500 16150
0

There are 0 best solutions below