[英]compare fields in two different django models
I am trying fill a field (hours) in Employee model based on the aggregate of a field (time_worked) in Timesheet model.我正在尝试根据 Timesheet 模型中的字段 (time_worked) 的聚合填充 Employee 模型中的字段(小时)。
MODELS.PY模型.PY
class Employee(models.Model):
...
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='employees')
hours = models.DurationField(null=True, blank=True)
class Timesheet(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
employee = models.ForeignKey(Employee, on_delete=models.CASCADE, null=True,)
time_worked = models.DurationField(null=True, blank=True)
I tried hours=Timesheet.objects.filter(employee=employee).aggregate(Sum('time_worked'))
我试过
hours=Timesheet.objects.filter(employee=employee).aggregate(Sum('time_worked'))
But when I try insert into Employee model that's where I get errors.但是当我尝试插入 Employee 模型时,我就会出错。
If I do this, Employee.objects.filter(id=employee).update(hours=hours)
, I get error "id expected a number but got Jacob".如果我这样做,
Employee.objects.filter(id=employee).update(hours=hours)
,我会收到错误“id 需要一个数字但得到了 Jacob”。 But id in Timesheet is actually a number (foreignkey).但是 Timesheet 中的 id 实际上是一个数字(外键)。
How do I add up the time_worked
in Timesheet
model of only employee A and insert the results into hours
column of Employee
model for employee A?如何将只有员工 A 的
Timesheet
模型中的time_worked
,并将结果插入到员工 A 的Employee
模型的hours
列中?
Or simply put, how do I match an employee in Timesheet to an employee in Employee?或者简单地说,我如何将 Timesheet 中的员工与 Employee 中的员工进行匹配?
Here's what I did to solve my problem.这是我为解决问题所做的工作。
class Employee(models.Model):
...
hours = models.DurationField(null=True, blank=True)
class TimeLog(models.Model):
...
employee = models.IntegerField(null=True, blank=True) # No foreignkey
time_worked = models.DurationField(null=True, blank=True)
def save( self, *args, **kwargs ):
employee_id = self.employee.pk #What's common for both models, very handy
#in the absence of a foreignkey
aggr_hours = TimeLog.objects.filter(employee=employee_id).values(
'employee').annotate(sum_hours=Sum(F('time_worked'),
output_field=DurationField()))
Employee.objects.filter(id=employee_id).annotate(total_hours=Subquery(
aggr_hours.values('sum_hours')[:1], output_field=DurationField()),
).update(hours=F('total_hours'))
super().save( *args, **kwargs )
Might not be wizardry but it's solid, and reliable可能不是巫术,但它坚固可靠
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.