Python Django跨反向关系聚合

Python Django跨反向关系聚合,python,django,sum,aggregates,Python,Django,Sum,Aggregates,这是与相关的,但略有不同 为了简单起见,假设我有模型(使用Django 1.7): 其中,对于特定的时间表/天,可以有多个OnCallEntry,每个OnCallEntry都有通话时间。我想查询员工工作的总小时数,以及通话的总分钟数 为此,我需要查询: query = TimesheetEntry.objects.all().filter(employee="John Smith").aggregate( total_hours = Sum('hours'),

这是与相关的,但略有不同

为了简单起见,假设我有模型(使用Django 1.7):

其中,对于特定的时间表/天,可以有多个OnCallEntry,每个OnCallEntry都有通话时间。我想查询员工工作的总小时数,以及通话的总分钟数

为此,我需要查询:

query = TimesheetEntry.objects.all().filter(employee="John Smith").aggregate(
            total_hours = Sum('hours'),
            total_oncall_minutes = Sum('oncallentry__minutes')
        )
但是,当给定时间表有多个OnCallEntry时,单个时间表的小时数乘以OnCallEntry的数量,导致总的_小时数总和出现偏差。(据我所知,这是由于django处理连接的方式)。当我不包括总通话时间部分时,它会按预期工作

对于total_hours部分,我只想得到不同时间表的总和。我更愿意在一个查询中完成这一切,因为在现实中,我有更多的聚合函数要与其他相关模型一起执行

我尝试过在中添加distinct关键字的所有变体,例如:

...Sum('hours', distinct=True)..
...Sum('oncallentry__minutes', distinct=True)..
...filter(employee="John Smith").distinct().aggregate(...
但这些似乎不起作用。任何帮助都将不胜感激

谢谢

...Sum('hours', distinct=True)..
...Sum('oncallentry__minutes', distinct=True)..
...filter(employee="John Smith").distinct().aggregate(...