按日期时间的月/日订购Django QuerySet? [英] Ordering a Django QuerySet by a datetime's month/day?

查看:199
本文介绍了按日期时间的月/日订购Django QuerySet?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个人的列表,每个人都有一个出生日期,可预见地存储在一个 DateField 中。我正在尝试创建这些人的列表,它们按照他们的出生(不考虑年份)的月份排序 - 有一种谁的生日是

I have a list of people, each person having a birthdate, which is predictably stored in a DateField. I'm trying to create a list of those people—sorted by the month and day of their birth (disregarding the year)—to have a sort of "who's birthday is coming up" display.

我似乎无法通过该人的 QuerySet > datetime.month 值。有没有办法可以做到这一点,而不必诉诸胁迫到一个列表()

I can't seem to order a QuerySet by the person's datetime.month value. Is there any way that this could be done without having to resort to coercing to a list()?

谢谢提前请让我知道问题需要澄清。

Thanks in advance and please let me know if the question needs clarification.

推荐答案

您可以使用 QuerySet.extra() 定义一个月字段并按它排序:

You can use QuerySet.extra() to define a month field and sort by it:

SomeModel.objects.extra(select={'birthmonth': 'MONTH(birthdate)'},
    order_by=['birthmonth']) 

这篇关于按日期时间的月/日订购Django QuerySet?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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