[Answered ]-Where to change the form of json response in django rest framework?

2👍

The first response appears to be a paginated response, which is determined by the pagination serializer. You can create a custom pagination serializer that will use a custom format. You are looking for something similar to the following:

class MetadataSerialier(pagination.BasePaginationSerializer):
    count = serializers.Field(source='paginator.count')
    next = NextPageField(source='*')
    previous = PreviousPageField(source='*')


class CustomPaginationSerializer(pagination.BasePaginationSerializer):
    metadata = MetadataSerializer(source='*')

This should give you an output similar to the following:

{
    "metadata": {
        "count": 2, 
        "next": null, 
        "previous": null
    },
    "results": [
        { "name": "somename", "description": "desc"},
        { "name": "someothername", "description": "asdasd"}
    ]
}

The pagination serializer can be set globally through your settings, as described in the documentation.

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_SERIALIZER_CLASS': {
        'full.path.to.CustomPaginationSerializer',
    }
}

Leave a comment