Django Rest Framework (DRF) How to set pagination

2019-07-26 22:58发布

问题:

I'm trying to use different sets of pagination classes on a viewset depending on query_params.

class BlockViewSet(viewsets.ModelViewSet):
    pagination_class = defaultPaginationClass

    def get_queryset(self):
        queryset = Block.objects.all()
        user = self.request.query_params.get('user', None)
        if user is no None:
           queryset = queryset.filter(user=user)
        return queryset

so if the get request is made to /block/, I want to use defaultPagination class while if the request is made to /block/?user=1, I want to use customPagination class.

回答1:

Try to redefine paginator property and if there is user query param, assign your custom pagination class to self._paginator

@property
def paginator(self):
    """
    The paginator instance associated with the view, or `None`.
    """
    if not hasattr(self, '_paginator'):
        if self.pagination_class is None:
            self._paginator = None
        else:
            user = self.request.query_params.get('user', None)
            if user is not None:
                self._paginator = customPaginationClass()
            else:
                self._paginator = self.pagination_class()
    return self._paginator

Final

class BlockViewSet(viewsets.ModelViewSet):
    pagination_class = defaultPaginationClass

    @property
    def paginator(self):
        """
        The paginator instance associated with the view, or `None`.
        """
        if not hasattr(self, '_paginator'):
            if self.pagination_class is None:
                self._paginator = None
            else:
                user = self.request.query_params.get('user', None)
                if user is not None:
                    self._paginator = customPaginationClass()
                else:
                    self._paginator = self.pagination_class()
        return self._paginator

    def get_queryset(self):
        queryset = Block.objects.all()
        user = self.request.query_params.get('user', None)
        if user is no None:
           queryset = queryset.filter(user=user)
        return queryset