Django Rest Framework(DRF)如何根据query_params设置分页类?

时间:2016-08-17 04:45:39

标签: python django pagination django-rest-framework

我试图在视图集上使用不同的分页类集,具体取决于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

所以如果get请求是/block/,我想使用defaultPagination类,而如果请求是/block/?user=1,我想使用customPagination类。

1 个答案:

答案 0 :(得分:3)

尝试重新定义paginator属性,如果有用户查询参数,请将自定义分页类指定为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

最终

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