How append sum of instances within a django querys

2020-04-20 07:47发布

问题:

I have a Django Queryset object that looks like this (it is a derived queryset, not a queryset for a Model):

<QuerySet [{'A': 2, 'B':3, 'C':0 }, {'A': 1, 'B':2, 'C':1 }]> 

How can I append a new instance containing sum of instances within the queryset to that queryset? That is, I need to make a new (or the same) queryset that looks like this:

<QuerySet [{'A':2, 'B':3, 'C':0 }, {'A':1, 'B':2, 'C':1 },
{'A':3, 'B':5, 'C':1 }]> 

回答1:

I don't think you can do that. But if you use aggregate then you will be able to get the sum of A, B, C like this:

>> result = YourModel.objects.aggregate(A=Sum('A'), B=Sum('B'), C=Sum('C'))
>> print(result)