Skip to content Skip to sidebar Skip to footer

How To Query From The Db By Age In Django When Birthday Is Stored As Year/month/day Fields

I have some code to filter and sort by age, that previously worked off of the assumption that the model we are querying over stored age as a single integer. These are the types of

Solution 1:

Since you're open to refactoring, I strongly recommend turning the birthdate into a single DateField rather than using three separate columns. Then you can do something like this:

from datetime import date
from django.utils.timezone import now

def age_range(min_age, max_age):
    current = now().date()
    min_date = date(current.year - min_age, current.month, current.day)
    max_date = date(current.year - max_age, current.month, current.day)

    return user_profiles.filter(birthdate__gte=max_date,
                                birthdate__lte=min_date).order_by("birthdate")

Most databases (not to mention Django) have built-in support for date and time fields, so it makes sense to use those when possible.

Post a Comment for "How To Query From The Db By Age In Django When Birthday Is Stored As Year/month/day Fields"