Gubbu
Gubbu

Reputation: 11

unsupported operand type(s) for +=: 'int' and 'Decimal128'

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.

Upvotes: 1

Views: 318

Answers (2)

Igor
Igor

Reputation: 155

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.

Upvotes: 0

Mukhtor Rasulov
Mukhtor Rasulov

Reputation: 587

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.

Upvotes: 1

Related Questions