Dasith
Dasith

Reputation: 363

Altering response in Django Rest

I have a ListAPIView that returns the json response below:

[
 {'name': 'Andrew'},
 {'name': 'Daniel'},
]

I want to alter it so that the response would look like:

{
 "Users": {
    [
     {'name': 'Andrew'},
     {'name': 'Daniel'},
    ]
 }
}

How could I do that?

EDIT: Below are is my serializer and the View

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('name',)

class UserReadView(ListAPIView):
    lookup_field = 'id'
    serializer_class = UserSerializer

Upvotes: 0

Views: 299

Answers (1)

neverwalkaloner
neverwalkaloner

Reputation: 47374

You can implement list method inside UserReadView and update response body inside it:

class UserReadView(ListAPIView):
    lookup_field = 'id'
    serializer_class = UserSerializer

    def list(self, request, *args, **kwargs):
        response = super().list(request, *args, **kwargs)
        return Response({'Users':{response.data}})

Upvotes: 3

Related Questions