List pagination in Django

91 Views Asked by At

I want to paginate a list of books. The api end point is like this /books?page=num&size=num So the number of page and how many books to load will be variables.

My response should look like:

{
  pagesnum= totalpages
  booksnum=totalbooks
  books=
  [ {detailsofbook1},
    {...},
    {...}
  ]
}

My code:

urlpattern:

path('api/books?page=<int:page>&size=<int:size>/',BookView.as_view()),

views.py

class BookView(APIView):
    http_method_names = ['get']
    permission_classes = (permissions.IsAuthenticated,)

    def index(request):
            books = Books.objects.all()

            books_per_page= request.GET.get('size')
            book_paginator = Paginator(books, books_per_page)

            page_num = request.GET.get('page')

            page = book_paginator.get_page(page_num)

            context = {
                'count': book_paginator.count(),
                'page': page
            queryset =Books.ojects.all()  
            }
            return JsonResponse(context, status=200)

This implementation doesn't work. First of all something is wrong probably with the url it doesnt seem to understand the variables. Or is something else wrong with my code?
1

There are 1 best solutions below

0
On BEST ANSWER

page and size are query parameters, so you get them by accessing request.query_params so it should be like

        books_per_page= request.query_params.get('size') # or request.query_params['size]
        page_num = request.query_params.get('page')

also, I'm a bit confused with index() I think your code should be in get(self, request, *args, **kwargs)

and my last thing is that you can make use of pagination in DRF, see