yedpodtrzitko
yedpodtrzitko

Reputation: 9359

Django: get aggregated value of two multiplied columns

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

Upvotes: 7

Views: 4626

Answers (3)

Antstud
Antstud

Reputation: 779

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

Upvotes: 3

trd
trd

Reputation: 91

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

Upvotes: 1

rinti
rinti

Reputation: 1273

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

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

Upvotes: 10

Related Questions