How to count people by age

Asked

Viewed 353 times

3

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 don’t know where to start.

1 answer

0

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

If I wanted to get 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
    # ...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.