Django CursorPagination用于按多个字段排序

时间:2019-04-03 14:35:33

标签: python django django-rest-framework

我正在使用Django DRF的CursorPagination延迟加载数据,目前我的目标是按多个字段对数据进行排序。

这是我的代码现在的样子:

class EndlessPagination(CursorPagination):

    ordering_param = ''

    def set_ordering_param(self, request):
        self.ordering = request.query_params.get(self.ordering_param, None)

        if not self.ordering:
            raise ValueError('Url must contain a parameter named ' + 
                             self.ordering_param)
        if self.ordering.startswith("\"") or self.ordering.endswith("\""):
            raise ValueError('Ordering parameter should not include quotation marks'    

    def paginate_queryset(self, queryset, request, view=None):
        # This function is designed to set sorting param right in the URL
        self.set_ordering_param(request)
        return super(EndlessPagination, self).paginate_queryset(queryset, request, view)

此代码适用于my_url/sms/270380?order_by=-timestamp这样的网址,但是如果我想按几个字段排序怎么办?

1 个答案:

答案 0 :(得分:2)

使用str.split()分割网址参数

class EndlessPagination(CursorPagination):
    ordering_param = 'order_by'

    def set_ordering_param(self, request):
        ordering_param_list = request.query_params.get(self.ordering_param, None)

        self.ordering = ordering_param_list.split(',')

        # here, "self.ordering" will be a "list", so, you should update the validation logic
        """
        if not self.ordering:
            raise ValueError('Url must contain a parameter named ' +
                             self.ordering_param)
        if self.ordering.startswith("\"") or self.ordering.endswith("\""):
            raise ValueError('Ordering parameter should not include quotation marks'
        """

    def paginate_queryset(self, queryset, request, view=None):
        # This function is designed to set sorting param right in the URL
        self.set_ordering_param(request)
        return super(EndlessPagination, self).paginate_queryset(queryset, request, view)


示例网址
1. my_url/sms/270380?order_by=-timestamp
2. my_url/sms/270380?order_by=-timestamp,name
3. my_url/sms/270380?order_by=-name,foo,-bar


UPDATE-1

首先感谢您提供了深入挖掘的机会:)

如您所说,我也没有在流行的API 中看到逗号分隔的query_params。因此,将url格式更改为

my_url/sms/270380??order_by=-name&order_by=foo&order_by=-bar
此时,request.query_params['order_by']将是等于 ['-name','foo','-bar'] 的列表。因此,您不想使用 split() 函数,因此您的set_ordering_param()方法变为

def set_ordering_param(self, request):
    self.ordering = request.query_params.get(self.ordering_param, None)
    #...... your other validations