我有以下在 SalesRecord 上运行的模型管理器:
def by_variety_and_date(self, start_date, end_date):
return self.model.objects.filter(
date__range=(start_date, end_date)
).values(
"variety"
).annotate(
qty_applied=Sum('qty_applied'),
margin=Avg('margin')
)
我真正想要的是margin=Avg('margin')
返回一个weighted平均,基于qty_applied
。有没有办法用 Django 的注释/聚合查询来做到这一点?我一直在尝试将 .aggregate() 串起来直到最后,但我仍然想要每个的平均值variety
如该查询集所描述。
本例中的模型如下所示:
class Sale(models.Model):
margin = models.DecimalField(null=True, blank=True, decimal_places=2, max_digits=12)
qty_applied = models.IntegerField(null=True, blank=True)
variety = models.ForeignKey(Variety, null=True)
totals = Totals()
EDIT
这就是我最终得到的结果。这有点奇怪,但它确实有效。
def by_variety_and_date(self, start_date, end_date):
return self.model.objects.filter(
date__range=(start_date, end_date)
).values(
"variety"
).annotate(
qty_applied=Sum('qty_applied'),
profit=Sum('profit'),
cogs=Sum('cogs'),
sales=Sum('value'),
margin=Sum(
(F('qty_applied')*F('margin')), output_field=FloatField()
) / Sum(
'qty_applied', output_field=FloatField())
)
我使用 F 对象作为@WTower https://stackoverflow.com/users/940098/wtower建议将每个对象的margin
由其qty_applied
,然后将整个东西包裹在一个Sum
并将其除以Sum
of the qty_applied
组中的所有对象。奇迹般有效!