Queryset of people with a birthday in the next X days

前端 未结 6 2138
天命终不由人
天命终不由人 2021-01-03 13:45

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.

6条回答
  •  借酒劲吻你
    2021-01-03 13:50

    Assuming a model like this--

    class Person(models.Model):
        name = models.CharField(max_length=40)
        birthday = models.DateTimeField() # their next birthday
    

    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.

提交回复
热议问题