Created
May 4, 2022 21:34
-
-
Save tubaman/9cfe083d7537a6a89afe335791075d77 to your computer and use it in GitHub Desktop.
Django Annotate Age from Birth Date
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.db import models | |
from django.db.models import Count, ExpressionWrapper, F, Case, When | |
from django.utils import timezone | |
class PersonQuerySet(models.QuerySet): | |
def with_age(self): | |
now = timezone.now() | |
age_expr = ExpressionWrapper( | |
Case( | |
When(birth_date__month__gte=now.month, birth_date__day__gt=now.day, then=now.year - F('birth_date__year') - 1), | |
default=now.year - F('birth_date__year'), | |
), | |
output_field=models.IntegerField() | |
) | |
return self.annotate(age=age_expr) | |
class Person(models.Model): | |
... | |
birth_date = models.DateField() | |
objects = PersonQuerySet.as_manager() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment