Django Datetime Field Query - Order by Time/Hour

前端 未结 1 1800
被撕碎了的回忆
被撕碎了的回忆 2020-12-21 18:19

I am performing a query to return all WorkOrders that have an appointment scheduled for today using the foreign key Appointment\'s datetime field <

1条回答
  •  时光说笑
    2020-12-21 19:00

    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.

    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, 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.

    0 讨论(0)
提交回复
热议问题