[Answered ]-How to get the sum of the prices of all items in the Magazine? – django ORM

1πŸ‘

βœ…

Start by taking a look at aggregations in Django.

It might look something like below:

from django.db.models import Sum
owners_magazines = Magazine.objects.filter(owner='Your owner')
total = 0;
for magazine in owners_magazines:
    item_values_with_total = magazine.items.values().annotate(total=Sum('item_price'))
    total += <Read appropriately from item_values_with_total>

You can use further try to group things together. The returned value will have a field called total which will have the required sum.

Edit –

You can try a non-ORM solution to understand it better

from django.db.models import Sum
    owners_magazines = Magazine.objects.filter(owner='Your owner')
    total = 0;
    for magazine in owners_magazines:
        all_items = magazines.items_set.all()
        for item in all_items:
            total += item.item_price

    print total

1πŸ‘

Use aggregation:

from django.db.models import Sum

for m in Magazine.objects.all():
   total = m.items_set.all().annotate(total=Sum('item_price'))
   print 'Total cost for items in {0} is {1}'.format(m,total)
πŸ‘€Burhan Khalid

Leave a comment