Django Rest Framework-是否可以在分页中添加排序

时间:2019-12-20 10:13:23

标签: django django-rest-framework

我有以下代码

class StandardResultsSetPagination(PageNumberPagination):
    page_size = 100
    page_size_query_param = 'page_size'
    max_page_size = 1000

class ListAllPrePayedV2(generics.ListAPIView):
    serializer_class = PrePayedSerializer
    pagination_class = StandardResultsSetPagination

    def get_queryset(self):
        queryset = PrePayed.objects

        # lcode
        lcode = self.request.query_params.get('lcode', None)
        if lcode is not None:
            queryset = queryset.filter(lcode=lcode)

        # lcode
        payed_by = self.request.query_params.get('payed_by', None)
        if payed_by is not None:
            queryset = queryset.filter(payed_by__icontains=payed_by)

        # order_by_date
        order_by_date = self.request.query_params.get('order_by_date', None)
        if order_by_date is not None:
            queryset = queryset.order_by('date')

        # order_by_payed_at
        order_by_payed_at = self.request.query_params.get('order_by_payed_at', None)
        if order_by_payed_at is not None:
            queryset = queryset.order_by('payed_at')

        if order_by_payed_at is None and order_by_date is None:
            queryset = queryset.order_by('pk')

        return queryset

问题是排序永远无法进行。这样的设置有可能还是我做错了什么?如果不可能的话,该怎么办?

2 个答案:

答案 0 :(得分:0)

尝试适用于我的

class StandardResultsSetPagination(PageNumberPagination):
    page_size = 100
    page_size_query_param = 'page_size'
    max_page_size = 1000

class ListAllPrePayedV2(generics.ListAPIView):
    queryset = PrePayed.objects.all()
    serializer_class = PrePayedSerializer
    pagination_class = StandardResultsSetPagination

    def get_queryset(self):

        # lcode
        lcode = self.request.query_params.get('lcode', None)
        if lcode is not None:
            queryset = PrePayed.objects.filter(lcode=lcode)

        # lcode
        payed_by = self.request.query_params.get('payed_by', None)
        if payed_by is not None:
            queryset = PrePayed.objects.filter(payed_by__icontains=payed_by)

        # order_by_date
        order_by_date = self.request.query_params.get('order_by_date', None)
        if order_by_date is not None:
            queryset = PrePayed.objects.order_by('date')

        # order_by_payed_at
        order_by_payed_at = self.request.query_params.get('order_by_payed_at', None)
        if order_by_payed_at is not None:
            queryset = PrePayed.objects.order_by('payed_at')

        if order_by_payed_at is None and order_by_date is None:
            queryset = PrePayed.objects.order_by('pk')

        return queryset

答案 1 :(得分:0)

除非我缺少任何东西,否则分页和顺序可以认为是彼此完全分开的。就订购而言,是否有任何理由不使用ordering provided by django-filter