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

sei*_*eki 1 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
Run Code Online (Sandbox Code Playgroud)

因此,如果向 发出 get 请求/block/,我想使用 defaultPagination 类,而如果向 发出请求/block/?user=1,我想使用 customPagination 类。

lev*_*evi 5

尝试重新定义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
Run Code Online (Sandbox Code Playgroud)

最终的

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
Run Code Online (Sandbox Code Playgroud)