我是初学者。我想获得员工年龄的列表> 25并计算员工的平均年龄。目前,我们需要从生日到年龄(我不知道它^^) 。请帮我创建一个关于它的示例QuerySet / Manager。
谢谢大家:))
我的模特:
class Employee(models.Model):
""""Employee model"""
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
birthday = models.DateField(max_length=8)
注意:未获得所有员工并从结果中过滤。 (results = Employee.objects.all()
)并且不使用Raw SQL。
答案 0 :(得分:1)
如果您正在寻找自定义经理,这里有一个建议。
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
然后使用
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 :(得分:0)
from datetime import date
from dateutil.relativedelta import relativedelta
qs = Employee.objects.filter(birthdate__gt=date.today() - relativedelta(years=+25))
预计25年+ 1天就足够了。函数relativedelta
由于闰年而使用,在02/29/2020不会引发ValueError异常。