How to annotate the age of a person based on their date of birth - Django
I am trying to annotate a simple Person
object with both the users date of birth and their age to keep the data normalised.
I am wishing to later perform some filtering with this annotation so a model property will not work.
I have found this blog article (last example) which seems to state what I'm wanting to do is possible, however whenever I actually execute this age
is always None
I am unsure what is going wrong here, logically it looks sound to me..
models.py
class Person(AbstractUser):
email = models.EmailField(unique=True)
date_of_birth = models.DateField(default=date.today())
views.py
class PersonViewSet(viewsets.ModelViewSet):
queryset = Person.objects.all()
serializer_class = PersonSerializer
permission_classes = [permissions.IsAdminUser]
def get_queryset(self):
queryset = self.queryset.annotate(
age = ExpressionWrapper(
ExtractDay(
ExpressionWrapper(
Value(datetime.now()) - F("date_of_birth"),
output_field=DateField(),
)
)
/ 365.25,
output_field=IntegerField(),
)
)
return queryset