yeNniE
yeNniE

Reputation: 35

Add new values at Django rest framework pagination

I want to add 'isSuccess' at the pagination returns.

For example,

{
    "count": 1234,
    "next": "http://mydomain/?page=2",
    "previous": null,
    "isSuccess" : 'Success'  # <---- this one
    "results": [
        {
          'id':123,
           'name':'abc'
        }, 
        {
          'id':234,
          'name':'efg'
        },
         ...
    ]
}

I found this way but It didn't work. How can I add new values at Django pagination return?

this is my try:

class Testing(generics.GenericAPIView):
    queryset = Problem.objects.all()
    serializer_class = userSerializer
    pagination_class = userPagination

    def get(self, request):
        queryset = self.get_queryset()
        page = self.request.query_params.get('page')

        if page is not None:
            paginate_queryset = self.paginate_queryset(queryset)
            serializer = self.serializer_class(paginate_queryset, many=True)

            tmp = serializer.data
            tmp['isSuccess'] = 'Success'

            return self.get_paginated_response(tmp)

Upvotes: 2

Views: 2093

Answers (2)

pppig
pppig

Reputation: 1275

You can try overriding the get_paginated_response method in the PageNumberPagination

Example:

from rest_framework.pagination import PageNumberPagination
from collections import OrderedDict


class CustomPagination(PageNumberPagination):

    def get_paginated_response(self, data):
        return Response(OrderedDict([
            ('count', self.page.paginator.count),
            ('next', self.get_next_link()),
            ('previous', self.get_previous_link()),
            ('results', data),

            ('isSuccess', "Success")  # extra
        ]))

Upvotes: 1

Sumithran
Sumithran

Reputation: 6555

Give this a try, instead of adding isSuccess to the serializer.data, add it to get_paginated_response().data

def get(self, request):
    queryset = self.get_queryset()
    page = self.request.query_params.get('page')

    if page is not None:
        paginate_queryset = self.paginate_queryset(queryset)
        serializer = self.serializer_class(paginate_queryset, many=True)

        tmp = serializer.data
        # tmp['isSuccess'] = 'Success'

        response = self.get_paginated_response(tmp)
        response.data['isSuccess'] = "Success"

        return Response(data=response.data, status=status.HTTP_200_OK)

    return Response(data="No Page parameter found", status=status.HTTP_200_OK)

The response will be something like

{
    "count": 1234,
    "next": null,
    "previous": null,
    "results": [
        {
          'id':123,
           'name':'abc'
        },
        ...
    ],
    "isSuccess" : 'Success'
}

Upvotes: 4

Related Questions