Search code examples
pythondjangosumaggregate

Aggregate Sum in Django. Sum of objects with the same name


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}>

Solution

  • have you tried the GROUP BY expression?

    UserProduct.objects.values("obj").annotate(sum=Sum('amount')).order_by("obj")