Django: get aggregated value of two multiplied columns

假装没事ソ 提交于 2019-12-03 08:11:37

You don't need that much raw SQL using extra().

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

As I answered here https://stackoverflow.com/a/36024089/4614802 the correct solution depends on django version.

  • For django < 1.8 use .aggregate(Sum('field1', field="field1*field2"))
  • For django >= 1.8 use .aggregate(Sum(F('field1')*F('field2'))
trd

This is sparta. In this way, if you want to print it somewhere in a template you have to use something like this:

{{ queryset.0.total }}

This was correctly answered here: Django Aggregation: Summation of Multiplication of two fields

The form is:

agg = Task.objects.all().aggregate(total=Sum('field1', field="field1*field2"))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!