0

Hey guys I have this serializer to get the list of pending users,

class UserInfo(serializers.ModelSerializer):
    class Meta:
        model       = Account
        fields      = ['id', 'username',]

class PendingRequestSerializer(serializers.ModelSerializer):
    other_user  = UserInfo(read_only=True)

    class Meta:
        model = PendingRequest
        fields = ['other_user', ]

views.py

class PendingRequestListApiView(APIView):
    permission_classes      = (IsAuthenticated,)

    def get(self, *args, **kwargs):
       user                 = PendingRequest.objects.filter(user=self.request.user)
       serializer           = PendingRequestSerializer(user, many=True)
       return Response(serializer.data, status=status.HTTP_200_OK)

I am getting the json response like this.

[
{
    "other_user": {
        "id": 8,
        "username": "testuser5"
    }
},
{
    "other_user": {
        "id": 4,
        "username": "testuser2"
    }
}

]

I want the json response to look like this instead.

"results": [
    {
        "id": 4,
        "username": "testuser2",
    },
    {
        "id": 8,
        "username": "testuser5",
    }
]

That is instead of having the user information in separate other_user, is it possible to combine it like it is in the second response?

Thanks

1 Answer 1

1

You can override to_representation() method of PendingRequestSerializer to return the other_user value

class PendingRequestSerializer(serializers.ModelSerializer):
        
    class Meta:
        model = PendingRequest

    def to_representation(self, instance):
        return UserInfo(instance.other_user).data
Sign up to request clarification or add additional context in comments.

2 Comments

It worked like a charm! can you please tell me what to_representation did there? Thanks a lot!
You're welcome. Glad to hear it worked. to_representation() is where the serialization is done - in this case where it is converted to JSON. By overriding the method, you tell it to return the serialized data of UserInfo class instead of PendingRequestSerializer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.