[Answered ]-Unsupported operand type(s) for +=: 'int' and 'Decimal128'

1👍

change the type of meal_amt variable into Decimal.

from decimal import Decimal

meal_data = Data.objects.filter(year= se_year, month= se_month, category = 'Meal')
meal_amt = Decimal(0)

for i in meal_data:
    meal_amt += i.amount

Also, no need to fetch the Data object in for loop.

0👍

You can just use the aggregate function to get the total sum like so:

from django.db.models import Sum

meal_amt = Data.objects.filter(
    year=se_year, 
    month=se_month, 
    category='Meal'
).aggregate(Sum('amount'))['amount__sum']

This should have better performance comparing with what you’re already doing since we are not looping through the records but getting the sum straight from the database instead.

👤Igor

Leave a comment