Django: Total birthdays each day for the next 30 days

后端 未结 4 943
遇见更好的自我
遇见更好的自我 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条回答
  •  -上瘾入骨i
    2021-01-03 17:13

    Something like this --

    from datetime import date, timedelta
    
    class Person(models.Model):
        name = models.CharField(max_length=40)
        birthday = models.DateField()
    
        @staticmethod
        def upcoming_birthdays(days=30):
            today = date.today()
            where = 'DATE_ADD(birthday, INTERVAL (YEAR(NOW()) - YEAR(birthday)) YEAR) BETWEEN DATE(NOW()) AND DATE_ADD(NOW(), INTERVAL %S DAY)'
            birthdays = Person.objects.extra(where=where, params=[days]).values_list('birthday', flat=True)
            data = []
            for offset in range(0, days):
                i = 0
                d = today + timedelta(days=offset)
                for b in birthdays:
                    if b.day == d.day and b.month == d.month:
                        i += 1
                data.append((d.day, i))
            return data
    
    print Person.upcoming_birthdays()
    

提交回复
热议问题