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.
- [Django]-In Django 1.7, Python3, using Floppyforms 1.3, keep getting error "TypeError: object() takes no parameters"
- [Django]-Django: how to filter on subset of many-to-many field?
- [Django]-Speeding up django server
- [Django]-Why does using .latest() on an empty Django queryset return…nothing?
Source:stackexchange.com