Bigbob556677
Bigbob556677

Reputation: 2158

Change Django Rest Framework Paginated Output Format

When serializing and paging using DRF the output of the API assumes the following format.

{
    "count": 4429,
    "next": "http://127.0.0.1:8000/data/component_log/?limit=100&offset=100",
    "previous": null,
    "results": [{...},{...},{...}]

}

This includes the count, next, and previous fields as well as the results field.

Is there any way to serialize and paginate while only returning the results array?

eg

[{...},{...},{...}]

My Serializer

class InvoiceSerializer(serializers.ModelSerializer):

    class Meta:
        model = Invoice
        fields = '__all__'

My ViewSet

class InvoiceViewSet(viewsets.ModelViewSet,UpdateModelMixin):

    queryset = Invoice.objects.all()
    serializer_class = InvoiceSerializer
    filter_backends = (OrderingFilter,)

Without paging you are able to achieve this with the following added to the REST_FRAMEWORK setting.

REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer'
    ),
}

but this does not carry over to paged requests.

Upvotes: 1

Views: 1577

Answers (1)

Ehsan Nouri
Ehsan Nouri

Reputation: 2040

use a Custom pagination class for your view and override the get_paginated_response method, like this:

from rest_framework.response import Response

class CustomPagination(pagination.PageNumberPagination):
    def get_paginated_response(self, data):
        return Response(data)

Upvotes: 3

Related Questions