我有这两个型号。我需要返回每个部门最老的员工名单。
class Employee(models.Model):
name = models.CharField(max_length=50)
birth_day = models.DateField()
department = models.ForeignKey('Department')
class Department(models.Model):
sector = models.CharField(max_length=255)
我有点担心如何在Django中制作它。
答案 0 :(得分:1)
我认为没有直接查询。您需要建立此类员工的名单。
empList = []
for dept in Department.objects.all() :
empList = empList + [dept.employee_set.order_by('birth_day')[0]]
#empList will have list oldest of employees.
答案 1 :(得分:0)
我认为这个决心。
empList = []
for dept in Department.objects.all() :
empList.append(dept.employee_set.latest('birth_day'))
但我也对更好的方法感兴趣,我正在想办法只做一个查询。
我试过了:
In [98]: d = Employee.objects.filter().annotate(Min('birth_day'))
In [99]: d.group_by = ['department_id']
In [100]: x = QuerySet(query=d, model=Employee)
(0.001) QUERY = 'SELECT "permissoes_employee"."id", "permissoes_employee"."name", "permissoes_employee"."birth_day", "permissoes_employee"."department_id", MIN("permissoes_employee"."birth_day") AS "birth_day__min" FROM "permissoes_employee" GROUP BY "permissoes_employee"."id", "permissoes_employee"."name", "permissoes_employee"."birth_day", "permissoes_employee"."department_id"' - PARAMS = (); args=()
但它不是仅仅由部门进行分组,而是忽略' group_by并以对所有字段进行分组结束,最终会产生错误的结果。
我认为我们没有比这更好的解决方案,只是为了使cursor.execute(" SQL")
:(