gpt4 book ai didi

python - Django QuerySet/Manager 从生日开始按年龄过滤员工

转载 作者:太空宇宙 更新时间:2023-11-04 02:40:14 25 4
gpt4 key购买 nike

我是初学者。我想列出年龄 > 25 的员工并计算员工的平均年龄。目前,我们需要从生日开始计算年龄(我不知道 ^^).请帮我创建关于它的示例查询集/管理器。

谢谢大家:))

我的模型:

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()) 并且不使用原始 SQL。

最佳答案

如果您正在寻找自定义管理器,这里有一个建议。

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)

关于python - Django QuerySet/Manager 从生日开始按年龄过滤员工,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46762933/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com