skip to Main Content

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


  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.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search