[Answered ]-How can I count item quantity per company? – queryset

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')):

Leave a comment