[Django]-Django calculate sum of column after multiplying each row with a different value

4👍

You should use F() expressions to multiply fields together, then use the __ operator in field names to reference foreign keys.

User.objects
  .filter(group=1)
  .aggregate(
    total_income=Sum(F('income') * F('country__currency__value')),
    total_expenditure=Sum(F('expenditure') * F('country__currency__value')),
  )

will return:

{'total_income': Decimal('18'), 'total_expenditure': Decimal('37')}

Leave a comment