简体   繁体   中英

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.

MODELS.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'))

But when I try insert into Employee model that's where I get errors.

If I do this, Employee.objects.filter(id=employee).update(hours=hours) , I get error "id expected a number but got Jacob". But id in Timesheet is actually a number (foreignkey).

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?

Or simply put, how do I match an employee in Timesheet to an employee in 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM