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
- [Answered ]-Should I use advance GeoDjango libraries for one simple calculation?
- [Answered ]-How do I pull a User object based on the attribute of a model it is associated with?
- [Answered ]-Validate dynamic checkboxes Django form
Source:stackexchange.com