I’m trying to add the numbers from the MongoDB database.
meal_data = Data.objects.filter(year= se_year, month= se_month, category = 'Meal')
meal_amt = 0
for i in meal_data:
id = i.id
m_amount_data = Data.objects.get(id = id)
meal_amt += m_amount_data.amount
TypeError: unsupported operand type(s) for +=: ‘int’ and ‘Decimal128’
The error is showing in this line.
meal_amt += m_amount_data.amount
I need to add those numbers and store them in a variable meal_amt
.
2
Answers
change the type of
meal_amt
variable into Decimal.Also, no need to fetch the Data object in for loop.
You can just use the
aggregate
function to get the total sum like so: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.