'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 1:[1]

You are writing an function based view, so that is why you need to do everything manually. If possible, you should rely on the provided generic base api views instead of attempting to re-write this:

class PostView(generics.ListAPIView):
    queryset = Post.objects.all()
    serializer_class = PostSerializer

path('posts', PostView.as_view(), name='posts_view')

To do it 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
    )

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andrew