April 27th, 2010

АШ

How to get or filter Django users by age range

The solution is very obvious, yet was not proposed by anyone on the IRC channel.

#! /usr/bin/env python
from datetime import date, timedelta
from humans.models import Human
"""
some constants
"""
today = date.today()
age_min = 10
age_max = 20
"""
date of maximum age is date of range start
"""
date_start = date(today.year - age_max - 1, today.month, today.day) + timedelta(days = 1)
date_end = date(today.year - age_min, today.month, today.day)
"""
date start should be not equal, just greater than
"""
humans_list = Human.objects.filter(
    birth_date__gt = date_start,
    birth_date__lte = date_end,
)