DJANGO Queryset : Calculate Sum of column

DJANGO


Use Aggregate function

 

from django.db.models import Sum

ItemPrice.objects.aggregate(Sum('price'))
# returns {'price__sum': 1000} for example

Note the return will return field value. To retrieve the sum use, 

sum = Sale.objects.filter(type='Flour').aggregate(Sum('column'))['column__sum']

Eg:
lv_div = stock_dividend_m.objects.filter(portfolio_id=portfolio_id,stocklist_id=stock_id).aggregate(Sum('divamt'))['divamt__sum']

 

Annotate will give the same result but the return is a queryset

Annotate
>> Order.objects.annotate(total_price=Sum('price'))
<QuerySet [<Order: L-555>, <Order: L-222>]>

>> orders.first().total_price
Decimal('340.00')

Aggregate
>> Order.objects.aggregate(total_price=Sum('price'))
{'total_price': Decimal('1260.00')}