Getting upcoming birthdays using 'date of birth' DateField

前端 未结 3 1662
醉梦人生
醉梦人生 2021-01-26 17:24

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

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


        
3条回答
  •  逝去的感伤
    2021-01-26 17:50

    Caveat: I believe calendars and time is hard. As a result, I feel obligated to warn you that I haven't rigorously tested my proposal. But of course, I think it should work. :)

    Unfortunately, I think you should abandon date objects as the additional complication of year data precludes easy selects. Rather, I propose storing the birthday as a MMDD string (comparison of strings works, as long as you format them consistently). You can then compute your next_20_days and convert that to a similar MMDD string, as well as today, then use them as values to compare against.

    I have three edge cases you should definitely make sure work:

    1. Normal month rollover. (e.g., June to July)
    2. Leap days -- don't forget to check presence as well as absence of Feb 29.
    3. Year boundary -- you'll need to either do two queries and union the results, or do an OR query using Q objects.

    Edit: See also:

    • How to store birthdays without a year part?
    • SQL Select Upcoming Birthdays
    • mySQL SELECT upcoming birthdays

    and so on. I just did a Google search for "stack overflow birthday select".

提交回复
热议问题