【问题标题】:How to make a queryset order_by and after that, make another order maintaining the result of the first one?如何创建一个查询集 order_by 并在此之后创建另一个订单来维护第一个订单的结果?
【发布时间】:2019-10-27 10:07:52
【问题描述】:

我需要对包含两列的查询集结果进行排序。 首先,我需要 order_by 'date'。对查询进行排序后,我需要对结果进行排序,并使用 order_by 'status' 保持第一顺序。

例子:


     date      status

2019-06-10 15:23:39 20


2019-06-12 15:37:31 20


2019-06-10 15:18:53 10


2019-06-12 15:38:01 10


2019-06-12 15:47:09 10


2019-06-12 15:36:30 0


2019-06-10 16:35:11 0


我需要以下结果:


     date      status

2019-06-12 15:37:31 20



2019-06-12 15:47:09 10


2019-06-12 15:38:01 10


2019-06-12 15:36:30 0


2019-06-10 15:23:39 20


2019-06-10 15:18:53 10


2019-06-10 16:35:11 0


关注 dkango 文档https://docs.djangoproject.com/en/2.0/ref/models/querysets/#order-by 我正在做一个 order_by 传递两个字段,如 order_by('-date', '-status')

我正在尝试以下代码

Measurements.objects.filter(patient=230).order_by('-date', '-status')

我的结果是:

         date      status
2019-06-12 15:47:09 10
2019-06-12 15:38:01 10
2019-06-12 15:37:31 20
2019-06-12 15:36:30 0
2019-06-10 16:35:11 0
2019-06-10 15:23:39 20
2019-06-10 15:18:53 10

我需要以下结果:

         date      status
2019-06-12 15:37:31 20
2019-06-12 15:47:09 10
2019-06-12 15:38:01 10
2019-06-12 15:36:30 0
2019-06-10 15:23:39 20
2019-06-10 15:18:53 10
2019-06-10 16:35:11 0

【问题讨论】:

    标签: django django-models django-views


    【解决方案1】:

    您需要先截断到DateTimeField 的日期。我们可以通过TruncDate [Django-doc] 做到这一点:

    from django.db.models.functions import TruncDate
    
    Measurements.objects.annotate(
        date_date=TruncDate('date')
    ).order_by('-date_date', '-status')

    源自 this 查询集的 Measurements 对象将有一个额外的属性 .date_datedate 截断到日期(所以时间是 0:00:00 然后)。

    【讨论】:

    • 这正是我想要的。非常感谢威廉,你太棒了。
    猜你喜欢
    • 2013-05-10
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-23
    • 2015-06-19
    • 2019-01-22
    • 1970-01-01
    相关资源
    最近更新 更多