1

I have written a code in Python using Django Rest Framework to fetch data from database(MySql) and view it in browser using Pagination(PageNumberPagination).It is working fine but the problem is the "count" is not coming in view. I want to show the total number of rows in count. I am getting response like this:

GET /fetchdata/?page=1&per_page=10

HTTP 200 OK
Allow: GET, OPTIONS, POST
Content-Type: application/json
Vary: Accept
[
    {
        "id": 53,
        "first_name": "Rounak",
    },
    {
        "id": 54,
        "first_name": "Rounak",   
    },
]

But I want the response like this.

HTTP 200 OK
{
    "count": 1023
    "next": "https://api.example.org/persons/?page=2&per_page=10",
    "previous": null,
    "results": [
       …
    ]
}

Below is my code, please suggest me something.

view.py

from rest_framework.pagination import PageNumberPagination
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from .pagination import StandardResultsSetPagination

@api_view(['GET','POST'])

def index(request):

  if request.method=='GET':

    all_dataobj=fetchdata.objects.all()

    paginator = StandardResultsSetPagination()
    result_page = paginator.paginate_queryset(all_dataobj, request)

    pserializer=fetchdataSerializers(result_page,many=True)

    return Response(pserializer.data,status=status.HTTP_201_CREATED)

  elif request.method=='POST':

    serializer=fetchdataSerializers(data=request.data)

  if serializer.is_valid():

    serializer.save()

  return Response(serializer.data,status=status.HTTP_201_CREATED)
  return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) 

pagination.py

from rest_framework import pagination

class StandardResultsSetPagination(pagination.PageNumberPagination):

  page_size = 10
  page_query_param = 'page'
  page_size_query_param = 'per_page'
  max_page_size = 1000

settings.py

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 
    'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10
}
A. J. Parr
  • 7,731
  • 2
  • 31
  • 46
Rounak Modak
  • 155
  • 1
  • 2
  • 14
  • 1
    You have to call **`get_paginated_response()`** method of Pagination class. – JPG Jun 24 '19 at 07:03
  • thanks a lotttt...it actually worked...I modified the response like this..."""" return paginator.get_paginated_response(pserializer.data) """"....Thanks @JPG – Rounak Modak Jun 24 '19 at 07:24
  • hey can you please help me out with one more thing...Its like I wanna do the same code but using LimitOffSetPagination in place of PageNumberPagination....so please tell me what changes do I need to make in my pagination.py , view.py and settings.py files.....please help....@JPG – Rounak Modak Jun 24 '19 at 07:57

0 Answers0