在接下来的X天生日快乐的人物 [英] Queryset of people with a birthday in the next X days
问题描述
在接下来的X天,我如何获得有生日的人的查询?我看到这个答案,但它确实
how do i get queryset of people with a birthday in the next X days? I saw this answer, but it does not suit me, because gets people only with current year of birth.
推荐答案
假设一个这样的模型 -
Assuming a model like this--
class Person(models.Model):
name = models.CharField(max_length=40)
birthday = models.DateTimeField() # their next birthday
下一步将是创建一个查询过滤掉任何记录生日有一个月和一天之间(现在今天,今天)和(当天,当天)。通过传递Person.objects.filter这样的关键字参数,您可以使用查询API实际访问datetime对象的月和日属性:birthday__month。我尝试了一个实际的queryset API方法,如birthday__month__gte,它失败了。所以我建议在每个(月,日)日期范围内生成一个月/日元组元的列表,然后将它们全部组合成一个django.db.models.Q的查询,如下所示: / p>
The next step would be to create a query filtering out any records with birthdays having a month and day in between (now.month, now.day) and (then.month, then.day). You can actually access the month and day attributes of the datetime object using the queryset API by passing Person.objects.filter a keyword argument like this: "birthday__month." I tried this with an actual queryset API method like "birthday__month__gte" and it failed though. So I would suggest simply generating a literal list of month/day tuples representing each (month, day) in the date range you want records for, then compose them all into a query with django.db.models.Q, like so:
from datetime import datetime, timedelta
import operator
from django.db.models import Q
def birthdays_within(days):
now = datetime.now()
then = now + timedelta(days)
# Build the list of month/day tuples.
monthdays = [(now.month, now.day)]
while now <= then:
monthdays.append((now.month, now.day))
now += timedelta(days=1)
# Tranform each into queryset keyword args.
monthdays = (dict(zip(("birthday__month", "birthday__day"), t))
for t in monthdays)
# Compose the djano.db.models.Q objects together for a single query.
query = reduce(operator.or_, (Q(**d) for d in monthdays))
# Run the query.
return Person.objects.filter(query)
调试完成后,应该返回一个查询每个具有生日的人,其月份和日期等于指定的元组列表中的任何一个月或几天。
After debugging, this should return a queryset with each person who has a birthday with month and day equal to any of the months or days in the specified list of tuples.
这篇关于在接下来的X天生日快乐的人物的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!