How to count person per age (Django)

155 views Asked by At

I have

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

and this 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 person per age

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

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

1

There are 1 answers

0
AlvaroAV On

In your case I would use 2 functions, one to obtain the age of the person, and another to prepare a dict that return persons grouped by age range.

def calculate_age(born):
    today = date.today()
    return today.year - born.year - ((today.month, today.day) < (born.month, born.day))

def get_persons_grouped_by_age():
    age_dict = {
        "under_20": [],
        "20_25": [],
        "25_30": [],
        "30_35": [],
        "35_40": [],
        "over_40": [],
    }

    for person in Person.objects.all():
        person_age = calculate_age(person.birthday)
        if person_age < 20:
           age_dict["under_20"].append(person)
        if 20 <= person_age < 25:
           age_dict["20_25"].append(person)
        elif 25 <= person_age < 30:
           age_dict["25_30"].append(person)
        elif 30 <= person_age < 35:
           age_dict["30_35"].append(person)
        elif 35 <= person_age < 40:
           age_dict["35_40"].append(person)
        else:
           age_dict["over_40"].append(person)

    return age_dict

An useful tip would be to add the calculate_age function to your Person model as a property like:

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

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

So you when you have a person object, you could do:

person.calculate_age()

and the return would be the age in years