Search code examples
pythondjangodjango-rest-frameworkdjango-pagination

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)

Solution

  • 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'
    }