我有点不高兴。我有一张桌子,上面有所有员工的合同信息。员工每次晋升或要续约时,可以在此表中拥有多个合同,将签定新合同。除此之外,员工可能会在任何时间离开公司,因此合同之间可能存在差距。
我想实现两件事:
服务年限,因此与员工签订的每份合同的期限合计
class Contract(models.Model):
user = models.ForeignKey(User, on_delete = models.CASCADE)
employment = models.ForeignKey(Employment, on_delete = models.CASCADE, null = True, blank = True)
jobgrade = models.ForeignKey(Jobgrade, on_delete = models.CASCADE, null = True, blank = True)
contract_start = models.DateField(null = True, blank = True)
contract_end = models.DateField(null = True, blank = True)
答案 0 :(得分:1)
您可以在Jobgrade
和Employee
模型类中使用属性方法,如下所示:
class Jobgrade(models.Model):
...
@property
def average_time(self):
# gets average time of of a Jobgrade
return self.contract_set.all().annotate(diff=F('contract_start')-F('contract_end')).aggregate(avg=Avg('diff'))['avg']
class Employee(models.Model):
...
@property
def get_length(self):
# gets sum time of of a Employee
return self.contract_set.all().annotate(diff=F('contract_start')-F('contract_end')).aggregate(sum=Sum('diff'))['sum']
在这里,我使用annotating表达式两次使用F之间的差异。然后,我用aggregation得到了sum和average。
现在,您可以在模板中使用这些值,例如:
{% for employee in Employee.objects.all %}
{{ employee.get_length }}
{% endfor %}
{% for job in Jobgrade.objects.all %}
{{ job.average_time }}
{% endfor %}