mario
mario

Reputation: 59

django how to sum item * quantity for each items in cart

How to sum each items in cart * quantity, example first item 10 *- quantity = total, The second one item x * quantity = total, this suma give me the total all items in cart not for each items.

def add_produktshitje(request, shitje_id):
shitje = get_object_or_404(Shitje, id=shitje_id)
suma= Produ.objects.filter(shitje_id=shitje.pk).aggregate(totals=Sum(F('sasia')*F('cmimi'), output_field=FloatField()))
return render(request, 'polls/add_produktshitje.html', {'shitje':shitje,'suma':suma})

Upvotes: 0

Views: 1037

Answers (1)

Francisco Ghelfi
Francisco Ghelfi

Reputation: 962

That´s because you are using "aggregate" wich is meant to get totals. You should use "annotate" to get the kind of partial aggregation you want.

Change this line

suma= Produ.objects.filter(shitje_id=shitje.pk).aggregate(totals=Sum(F('sasia')*F('cmimi'), output_field=FloatField()))

for this line

suma= Produ.objects.filter(shitje_id=shitje.pk).values("product_name").annotate(totals=Sum(F('sasia')*F('cmimi'), output_field=FloatField()))

Note that I added values("product_name"), this way you choose the field on which you are going to group yor annotation. I just put "product_name" couse you mentioned a cart, but replace that string fro whatever field your need.

https://docs.djangoproject.com/en/2.2/topics/db/aggregation/#generating-aggregates-for-each-item-in-a-queryset

Hope this helps.

Upvotes: 1

Related Questions