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
π€Pratik Mandrekar
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
- [Answered ]-How to keep the query set (filter/search) in a list after returning from add/change/delete
- [Answered ]-How to sync django models with pre-existing database?
- [Answered ]-Django haystack, no url in search results
- [Answered ]-Django Rest Framework render_form & required fields
- [Answered ]-Confused with virtual environments in python django
Source:stackexchange.com