djangodjango-rest-frameworkdjango-pagination

Django rest how to do pagination with PageNumberPagination


I wrote the following codes. But when I go to the url posts?page=1, it still shows all of the Post model objects. What should I do?


settings.py

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10
}

ursl.py

path('posts', views.posts_view, name='posts_view')

views.py

@api_view(['GET'])
def posts_view(request):
    posts = Post.objects.all()
    serializer = PostSerializer(posts, many=True)
    return Response(serializer.data)

Solution

  • You are writing a function based view, using @api_view, so you need to do the pagination manually. You can try using the provided generic base api views instead of attempting to re-write this, if it works in your situation:

    class PostView(generics.ListAPIView):
        queryset = Post.objects.all()
        serializer_class = PostSerializer
        pagination_class = PageNumberPagination
    
    path('posts', PostView.as_view(), name='posts_view')
    

    To do pagination manually you are going to need to create and invoke the pagination just like the base classes do:

    def my_view(request):
        qs = Post.objects.all()
        pagination = PageNumberPagination()
        page = pagination.paginate_queryset(qs, request)
        serializer = PostSerializer(page, many=True)
        return pagination.get_paginated_response(
            serializer.data
        )
    

    To be clear, using @api_view does support other framework features using additional decorators, e.g. @permissions_classes. View level features like pagination & filtering are not supported via decorators.