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
}