问题
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