[Django]-Django QuerySet/Manager filter employees by age from birthday

3👍

If you are looking for custom managers here is one suggetion.

import datetime
from django.db import models

# Create your models here.


class EmployeeManager(models.Manager):
    def get_queryset(self):
        return super(EmployeeManager, self).get_queryset()

    def get_queryset_age_greater_25(self):
        # The `iterator()` method ensures only a few rows are fetched from the database at a time, saving memory.
        ids = [obj.id for obj in self.get_queryset().iterator() if obj.find_age() > 25]
        return self.get_queryset().filter(id__in=ids)

    def get_avg(self):
        sum_, count = sum(
            map(lambda obj: obj.find_age(), self.get_queryset_age_greater_25().iterator())), self.get_queryset_age_greater_25().count()
        return sum_/count


class Employee(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    birthday = models.DateField(max_length=8)
    objects = EmployeeManager()

    def find_age(self):
        return datetime.date.today().year - self.birthday.year

Then use

Employee.objects.get_queryset_age_greater_25() # to get employee objects having age greater than 25)
Employee.objects.get_avg() # to get avg age of employees having age greater than 25)

1👍

from datetime import date
from dateutil.relativedelta import relativedelta

qs = Employee.objects.filter(birthdate__gt=date.today() - relativedelta(years=+25))

Expected that 25 years + 1 day is enough. The function relativedelta is used due to leap-year, to not raise ValueError exception on 02/29/2020.

Leave a comment