Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django rest framework: how to turn off/on pagination in ModelViewSet

I'm using Django REST framework with djangorestframework-csv with default pagination settings, but when request is with format "CSV", there is no need in paginaion. Is possible to disable pagination with:

pagination_class = None

it's possible to change it dynamically?

class ObjectViewSet(BaseViewSet, viewsets.ModelViewSet):

    queryset = Object.objects.none()
    serializer_class = ObjectSerializer
    pagination_class = None # if format is "CSV"
    # pagination_class = None # if fromat isn't "CSV"

Thanks.

like image 358
Danila Kulakov Avatar asked Jun 05 '17 13:06

Danila Kulakov


3 Answers

This solution is working for me

DRF Version: 3.11.0

Django Version: 2.2.7

By default pagination is working but when I will pass the query param 'no_page' then pagination will be disabled: like: http://localhost:8000/api/city/?no_page

class CityListView(generics.ListCreateAPIView):
    serializer_class = serializers.CitySerializer
    def paginate_queryset(self, queryset, view=None):
        if 'no_page' in self.request.query_params:
            return None
        else:
            return self.paginator.paginate_queryset(queryset, self.request, view=self)
like image 155
miftkhar Avatar answered Nov 04 '22 09:11

miftkhar


One option would be to dynamically disable pagination on the view by setting a no_page query parameter:

def paginate_queryset(self, queryset, request, view=None):
    if 'no_page' in request.query_params:
        return None

    return super().paginate_queryset(queryset, request, view)
like image 17
Meistro Avatar answered Nov 04 '22 11:11

Meistro


if you just want to turn on or off pagination by client dynamically,you can custom Pagination class as:

class Pagination(PageNumberPagination):
    page_size_query_param = 'page_size'
    max_page_size = 100

    def get_page_size(self, request):
        if self.page_size_query_param:
            page_size = min(int(request.query_params.get(self.page_size_query_param, self.page_size)),
                        self.max_page_size)
            if page_size > 0:
                return page_size
            elif page_size == 0:
                return None
            else:
                pass
        return self.page_size

use this class as your pagination_class and you can turn off pagination by request url "http://www.example.com/some_object/?page_size=0", ?page_size=0 will disable pagination. if you just want disable pagination when request format is CVS,you can try what danilke said.

like image 7
Ykh Avatar answered Nov 04 '22 11:11

Ykh