在接下来的X天中有生日的人的查询集

Use*_*ser 2 python django datetime django-models django-queryset

如何在接下来的X天获得有生日的人的查询集?我看到了这个答案,但它并不适合我,因为只有当前出生年份的人才能获得.

twn*_*ale 6

假设这样的模型 -

class Person(models.Model):
    name = models.CharField(max_length=40)
    birthday = models.DateTimeField() # their next birthday
Run Code Online (Sandbox Code Playgroud)

下一步是创建一个查询,过滤掉生日中包含一个月和日的任何记录(now.month,now.day)和(then.month,then.day).您可以使用queryset API实际访问datetime对象的月和日属性,方法是将Person.objects.filter传递给像这样的关键字参数:"birthday__month".我尝试使用像"birthday__month__gte"这样的实际查询集API方法,但它失败了.所以我建议只生成一个月/日元组的文字列表,代表你想要记录的日期范围中的每个(月,日),然后用django.db.models.Q将它们全部组成一个查询,如下所示:

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)
Run Code Online (Sandbox Code Playgroud)

在调试之后,这应该返回一个查询集,其中每个人的生日月份和日期等于指定的元组列表中的任何月份或日期.