Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to paginate response from function based view of django rest framework?

I have written a code snippet like below, i need to achieve pagination in this, kindly let me know how is it possible. Also due to some reasons i want to use only function based views.

@api_view(['GET'])
@permission_classes([AllowAny])
def PersonView(request):
    context={'request': request}
    person_objects = Person.objects.all()
    if len(person_objects) > 0:
        person_data = PersonSerializer(person_objects, many=True, context=context)
        return Response(person_data.data, status=status.HTTP_200_OK)
    else:
        return Response({}, status=status.HTTP_200_OK)
like image 213
Nirmal Vatsyayan Avatar asked Dec 02 '15 12:12

Nirmal Vatsyayan


2 Answers

http://www.django-rest-framework.org/api-guide/pagination/

from rest_framework.pagination import PageNumberPagination

@api_view(['GET',])

@permission_classes([AllowAny,])

def PersonView(request):

    paginator = PageNumberPagination()
    paginator.page_size = 10
    person_objects = Person.objects.all()
    result_page = paginator.paginate_queryset(person_objects, request)
    serializer = PersonSerializer(result_page, many=True)
    return paginator.get_paginated_response(serializer.data)
like image 54
Geo Jacob Avatar answered Sep 19 '22 15:09

Geo Jacob


You can also define custom pagination class by overriding PageNumberPagination

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

it will help to define

page_size, page query custom parameters and max_page_size

views.py

from rest_api.pagination import StandardResultsSetPagination

@api_view(['GET',])
@permission_classes([AllowAny,])
def PersonView(request):
    person_objects = Person.objects.all()
    if len(person_objects)> 0:
        paginator = StandardResultsSetPagination()
        result_page = paginator.paginate_queryset(person_objects, request)
        serializer = PersonSerializer(result_page, many=True)
        return paginator.get_paginated_response(serializer.data)
    else:
        return Response({},status=status.HTTP_200_OK)

Eg: Request

GET https://api.example.org/persons/?page=1&per_page=10

Response

HTTP 200 OK
{
    "count": 1023
    "next": "https://api.example.org/persons/?page=2&per_page=10",
    "previous": null,
    "results": [
       …
    ]
}
like image 37
vijay Avatar answered Sep 20 '22 15:09

vijay