按created_at字段对合并的QuerySets进行排序

时间:2018-02-15 12:54:21

标签: python django django-views

我尝试按created_at字段和DESC(从max到min)对两个合并的QuerySet进行排序:

# app/views.py

class AccountIndexView(View):

    template_name = 'accounts/accounts_index.html'

    def get(self, request):
        # Get TVS object
        obj_1 = ModelOne.objects.filter(user=request.user)
        obj_2 = ModelTwo.objects.filter(user=request.user)

        # Make orders object
        orders = sorted(
            chain(obj_1, obj_2),
            key=attrgetter('created_at')
        )

        return render(request, self.template_name, {'orders': orders})

但是这种方式不起作用:QuerySet仍然按ID和ASC排序(从最小到最大)。如何用我的案子解决这个问题?

1 个答案:

答案 0 :(得分:0)

好的,我在Python Docs中创建了解决方案:

  

list.sort()sorted()都接受带有布尔值的reverse参数。这用于标记降序排序。例如,要以反向年龄顺序获取学生数据:

>>> student_tuples = [('jane', 'B', 12), ('dave', 'B', 10), ('john', 'A', 15)]
>>> sorted(student_tuples, key=itemgetter(2), reverse=True)
[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]

请参阅:https://docs.python.org/3/howto/sorting.html#ascending-and-descending