使用“出生日期”DateField即将到来的生日 [英] Getting upcoming birthdays using 'date of birth' DateField

查看:495
本文介绍了使用“出生日期”DateField即将到来的生日的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图在即将到来的20天内获得生日,以下人员型号:

I'm trying to get the birthdays in the upcoming 20 days, given the below Person model:

class Person(models.Model):
    dob = models.DateField()  # date of birth

SO已经有类似的问题了(这里 here ),但是这些不覆盖我的用例,因为我正在存储出生日期而不是下一个生日或时间段。

There are similar questions on SO already (here and here), but these do not cover my use case, as I'm storing a date of birth instead of the next birthday or a timefield.

我试图做一些如下的事情:

I've tried to do some things like the following:

from datetime import timedelta, date
today = date.today()
next_20_days = today+timedelta(days=20)
Person.objects.filter(dob__month=today.month, dob__day__range=[today.day, next_20_days.day])

...但我得到 FieldError:DateField不支持查找'day'或不允许加入字段。

当我做例如 Person.objects.filter(dob__month = today.month,dob__day = next_20_days.day),我从现在开始获得了20天的结果。所以我有可能在一个循环中过去的每一个20天,但这似乎是无效的。

When I do e.g. Person.objects.filter(dob__month=today.month, dob__day=next_20_days.day), I do get the results for exactly 20 days from now. So I potentially could go over each of the 20 days in a loop, but that seems rather ineffective.

有什么想法如何做到这一点吗? >

Any idea on how to do this the proper way?

推荐答案

FYI,我最终做了以下工作,适用于我,哪些不需要原始SQL。
欢迎任何改进: - )

FYI, I ended up doing the following which works for me and which does not require raw SQL. Any improvements would be welcomed :-)

# Get the upcoming birthdays in a list (which is ordered) for the amount of days specified
def get_upcoming_birthdays(person_list, days):
    person_list= person_list.distinct()  # ensure persons are only in the list once
    today = date.today()
    doblist = []
    doblist.extend(list(person_list.filter(dob__month=today.month, dob__day=today.day)))
    next_day = today + timedelta(days=1)
    for day in range(0, days):
        doblist.extend(list(person_list.filter(dob__month=next_day.month, dob__day=next_day.day, dod__isnull=True)))
        next_day = next_day + timedelta(days=1)
    return doblist

这篇关于使用“出生日期”DateField即将到来的生日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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