这与这个问题有关,但略有不同。
为简单起见,假设我有模型(使用 Django 1.7):
class TimesheetEntry(models.Model):
date = models.DateField()
employee = models.CharField(max_length=255)
hours = models.FloatField()
class OnCallEntry(models.Model)
timesheet = models.ForeignKey(TimesheetEntry)
minutes = models.FloatField()
comment = models.CharField(max_length=255)
对于特定的 TimesheetEntry/day,可以有多个 OnCallEntry,每个都包含在通话中花费的分钟数。我想查询员工工作的所有时间的总和,以及待命的总分钟数。
为此,我有以下查询:
query = TimesheetEntry.objects.all().filter(employee="John Smith").aggregate(
total_hours = Sum('hours'),
total_oncall_minutes = Sum('oncallentry__minutes')
)
但是,当给定 TimesheetEntry 有多个 OnCallEntry 时,单个 TimesheetEntry 的小时数会乘以 OnCallEntries 的数量,从而导致 total_hours Sum 出现偏差。(根据我的阅读,这是由于 django 处理连接的方式)。当我不包括 total_oncall_minutes 部分时,它按预期工作。
对于 total_hours 部分,我只想获取不同 TimesheetEntries 的总和。而且我更愿意在一个查询中完成所有操作,因为实际上我有更多想要执行的聚合函数以及其他相关模型。
我已经尝试了添加 distinct 关键字的所有变体,例如:
...Sum('hours', distinct=True)..
...Sum('oncallentry__minutes', distinct=True)..
...filter(employee="John Smith").distinct().aggregate(...
但这些似乎不起作用。任何帮助,将不胜感激!
谢谢