Skip to content

Instantly share code, notes, and snippets.

@LowerDeez
Created November 2, 2020 11:13
Show Gist options
  • Save LowerDeez/c35ced782ecc997ccadbe06a868f9937 to your computer and use it in GitHub Desktop.
Save LowerDeez/c35ced782ecc997ccadbe06a868f9937 to your computer and use it in GitHub Desktop.
Annotate age for user from birthday
from django.db.models import (
Avg,
Count,
DateField,
ExpressionWrapper,
F,
IntegerField,
Min,
Q,
Value
)
from django.db.models.functions import ExtractDay
qs = (
EventEntryChild.objects
.annotate(
years_age=ExpressionWrapper(
ExtractDay(
ExpressionWrapper(
Min('event_entry__dates__date') - F('child__birthday'),
output_field=DateField()
)
)
/
365.25,
output_field=IntegerField()
),
)
.values('years_age')
.filter(years_age__isnull=False)
.annotate(
town=F('event_entry__event__town__title'),
)
.annotate(total=Count('years_age'))
.order_by('town', 'years_age')
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment