如何正确地将django中的查询集中的值相乘

时间:2018-02-23 09:47:31

标签: django python-3.x django-rest-framework

我想在queryset中乘以两个值,如何实现这一目标: 这就是我所拥有的:

def get_adjustment(self):
        Adjustment.objects.filter(employee_month_id=1,adjustment_type=2)
        .values('exchange_rate','amount').aggregate(Sum('amount', field="exchange_rate*amount") 

2 个答案:

答案 0 :(得分:3)

您需要使用F()个对象。

.values('exchange_rate','amount').aggregate(Sum(F('amount') * F('exchange_rate')))

请参阅query expressions文档。

答案 1 :(得分:1)

obj = SomeModel.objects.filter(** something).extra(     select = {' total':' SUM(one_column * another_column)'}, )

<强> Adjustment.objects.filter(employee_month_id = 1,ADJUSTMENT_TYPE = 2)         .values(&#39; exchange_rate&#39;,&#39;金额&#39;)。额外(select = {&#39; total&#39;:&#39; SUM(exchange_rate * amount)&#39; })