Django Datetime字段查询-按时间/小时排序 [英] Django Datetime Field Query - Order by Time/Hour

查看:466
本文介绍了Django Datetime字段查询-按时间/小时排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在执行查询以使用外键约会 WorkOrder >的日期时间字段开始。这是我正在使用的查询,它正在按预期方式工作。

I am performing a query to return all WorkOrders that have an appointment scheduled for today using the foreign key Appointment's datetime field start. This is the query I am using and it is working exactly as expected.

WorkOrder.objects.filter(appointment__start__year=date.today().year, appointment__start__month=date.today().month, appointment__start__day=date.today().day)

我想按日期降序和小时升序对它们进行排序。
我想要的订单应如下所示:

I would like to sort them by date descending and hour ascending. The order I want would look something like this:

11-May-2014 08:00
11-May-2014 10:00
11-May-2014 12:00
10-May-2014 10:00
10-May-2014 13:00
09-May-2014 15:00
...

我尝试使用以下命令订购它为:

I have tried ordering it with commands such as:

.order_by("-appointment__start", "appointment__start__hour")

,但这会导致以下错误:

but that results in the following error:

FieldError: Join on field 'start' not permitted. Did you misspell 'hour' for the lookup type?

似乎我只能做

.order_by("-appointment__start")

还有另一种方式

推荐答案

您是否正在使用Django版本< 1.6?因为 datetime 字段在 hour 之前按已在1.6中添加。如果是这样,那么很遗憾,您将无法以这种方式访问​​小时。但是,您可以使用该方法访问

Are you using a Django version < 1.6? Because datetime field lookups by hour were added in 1.6. If so, then unfortunately you won't be able to access the hour in that way. However, you can use that method to access the day.

因此,您可以更改 order_by

Thus, you can change your order_by to:

.order_by("appointment__start", "-appointment__start__day")

这将首先按日期时间升序排列(这将花费数小时),

This will first order by datetime ascending (which will take care of hours) and then day descending.

OR ,您可以使用 extra() 修饰符进行选择从日期时间开始的小时数,并以此排序。 下面是从日期时间中选择月份的示例。但是,由于 ForeignKey ,会更加复杂。

OR, you can use the extra() modifier to select the hour from the datetime and order by it. Here's an example selecting month from a datetime. However, it will be a bit more complicated due to the ForeignKey.

这篇关于Django Datetime字段查询-按时间/小时排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆