Django: Total birthdays each day for the next 30 days

后端 未结 4 967
遇见更好的自我
遇见更好的自我 2021-01-03 16:35

I\'ve got a model similar to this:

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


        
4条回答
  •  暖寄归人
    2021-01-03 17:24

    (Queryset of people with a birthday in the next X days) Found cool solution for this! For me it works!

    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)
    

    But it get a list of persons that have a birthday in date range. You should change a bit.

提交回复
热议问题