How append sum of instances within a django queryset to that queryset?

試著忘記壹切 提交于 2020-01-11 11:32:42

问题


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)


来源:https://stackoverflow.com/questions/58809355/how-append-sum-of-instances-within-a-django-queryset-to-that-queryset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!