1👍
✅
If you want to calculate the quantity sum of all items for every company, you can do:
Company.objects.annotate(quantity_sum=Sum('item_set__quantity'))
The result is a queryset where every object (Company instance) has an attribute ‘quantity_sum’ representing the information you want.
1👍
Use django aggregation on backward relationship:
for company in Company.objects.annotate(total_qty=Sum('item__quantity')):
print company, company.total_qty
Note, that you can use any filter on Company
model as usual. For example:
us_companies = Company.objects.filter(contry='US') \
.annotate(total_qty=Sum('item__quantity')):
- [Answered ]-NoReverseMatch in Django url
- [Answered ]-Django REST API custom methods for generic views
- [Answered ]-How to duplicate a record with all dependencies?
- [Answered ]-Django template/view issues with carousel
- [Answered ]-How to register a new Model in Django-Oscar Dashboard?
Source:stackexchange.com