How to count people by age

2

I have

class Person(TimeStampedModel, Address):
    name = models.CharField(_('nome'), max_length=100)
    birthday = models.DateField(_('data de nascimento'))

and the function

import datetime
from datetime import date

'''
http://keyes.ie/calculate-age-with-python/
'''


def age(when, on=None):
    if on is None:
        on = datetime.date.today()
    was_earlier = (on.month, on.day) < (when.month, when.day)
    return on.year - when.year - (was_earlier)

age(date(2000, 1, 1))

How to count people by age range?

age quant
20-25   89
25-30   100
30-35   90
35-40   102

I know I have to use annottate and count, but I do not know where to start.

    
asked by anonymous 08.06.2015 / 08:53

1 answer

0

Using annotante I could not extract the year and month using F('birthday') to perform the calculation.

If I wanted to take the track it would be something like this:

model

class Person(TimeStampedModel, Address):
    name = models.CharField(_('nome'), max_length=100)
    birthday = models.DateField(_('data de nascimento'))

    def idade(self):
        hoje = date.today()
        return hoje.year - self.birthday.year - ((hoje.month, hoje.day) < (self.birthday.month, self.birthday.day))

view

faixa = {'vinte_vintecinco': 0, 'vintecinco_trinta': 0, ...}
pessoa = Person.objects.filter(birthday__isnull=False)
for p in pessoas:
    if 20 >= p.idade <= 25:
        faixa['vinte_vintecinco'] += 1
    # ...
    
08.06.2015 / 17:46