2

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)
yeNniE
  • 35
  • 5

2 Answers2

3

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'
}
Sumithran
  • 6,217
  • 4
  • 40
  • 54
  • Also, "results" can be moved to the end of JSON with `data.move_to_end('results')`. Might be helpful for manual api browsing if results contain a long list – Serguei A Mar 22 '23 at 16:24
1

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
        ]))

pppig
  • 1,215
  • 1
  • 6
  • 12