7

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'))
Cœur
  • 37,241
  • 25
  • 195
  • 267
yedpodtrzitko
  • 9,035
  • 2
  • 40
  • 42

3 Answers3

10

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

obj = SomeModel.objects.filter(**something).extra(
    select = {'total': 'SUM(one_column * another_column)'},
)
rinti
  • 1,273
  • 1
  • 12
  • 16
3

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'))
Community
  • 1
  • 1
Antstud
  • 729
  • 7
  • 3
1

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"))
Community
  • 1
  • 1
trd
  • 95
  • 1
  • 8