Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set dynamic page_size in DRF PageNumberPagination

In class PostByFilters, I'm getting limit as a url parameter, and I want to assign the value into page_size in class BasicSizePagination. I tried to use global variable outside of the two classes, but it didn't work. Is there anyway reinitialize the BasicSizePagination in PostByFilters so that I can directly assign the value in PostByFilters?

class BasicSizePagination(pagination.PageNumberPagination):
    page_size = 10

class PostByFilters(ListAPIView):
    serializer_class = serializers.PostSerializer
    pagination_class = BasicSizePagination

    def get_queryset(self):

        limit = self.request.query_params.get('limit', None)
        ...

        return queryset
like image 860
Jae P. Avatar asked Dec 13 '18 23:12

Jae P.


1 Answers

Create a new Pagination class from PageNumberPagination and override page_size_query_param attribute as below

from rest_framework.pagination import PageNumberPagination


class CustomPageNumberPagination(PageNumberPagination):
    page_size_query_param = 'size'  # items per page

Hence your URL will be, /api/foo/?size=10 , this will return 10 items per page. If you not providing the size argument in the URL, DRF will use settings.PAGE_SIZE

like image 107
JPG Avatar answered Nov 03 '22 17:11

JPG