Django: get aggregated value of two multiplied columns

非 Y 不嫁゛ 提交于 2019-12-20 23:26:08

问题


I need to get aggregated value of two columns. So first multiple them together and then get theirs sum(). Code below naturally does not work, it is just for clarification.

Is it somehow possible or should I use raw SQL?

SomeModel.objects
    .filter(**something)
    .aggregate(Sum('one_column' * 'another_col'))

回答1:


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

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



回答2:


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'))



回答3:


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"))


来源:https://stackoverflow.com/questions/1875153/django-get-aggregated-value-of-two-multiplied-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!