Django Rest Framework (DRF) How to set pagination

2019-07-26 22:41发布

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条回答
叼着烟拽天下
2楼-- · 2019-07-26 23:26

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
查看更多
登录 后发表回答