I have the following QuerySet, this is a shopping list:
<QuerySet
[
<Cart_object: {name: 'Apple', amount: 10}, {name: 'Bananas', amount: 20},
<Cart_object: {name: 'Bananas', amount: 10}>
]
>
I apply the following code to it, and I get the sum of all products for each of the objects:
for obj in cart:
from_cart = UserProduct.objects.filter(obj=obj).aggregate(Sum('amount'))
print(from_cart)
Out:
{'amount__sum': 30}
{'amount__sum': 10}
The question is as follows. How to use aggregate (Sum ('amount')) to add only those objects that have the same 'name'. To get one Cart_object, in which 'Apple' = 10, and 'Bananas' = 30 (Since there are records with the same name)
<Cart_object: {name: 'Apple', amount: 10}, {name: 'Bananas', amount: 30}>
CodePudding user response:
have you tried the GROUP BY expression?
UserProduct.objects.values("obj").annotate(sum=Sum('amount')).order_by("obj")
CodePudding user response:
The SQL command for this, is SELECT "userproduct"."name", SUM("userproduct"."amount") AS "the_amount" FROM "table" GROUP BY "userproduct"."name"
.
What you can have with Django by doing:
from django.db.models import Sum
UserProduct.objects.values('name').annotate(the_amount=Sum('amount'))