I have the following Models set up in my app:
- Lesson
- Student
- Evaluation
The Lesson and Student models have a many-to-many relationships through Evaluation. In the Evaluation model, I also store the fee received for the lesson. I know I should really store this in the Lesson model and then multiply by the number of students but sometimes for whatever reason a student may not pay the full amount for a lesson, so I need to keep track of it on an individual basis.
I'm trying to create a list of all lessons in a given time period and include a column which displays
- The total amount received for the lesson
- The total amount received for all lessons in that time period.
At the moment, I am just using a generic view to return all lessons and I have a simple开发者_Python百科 method defined in my Lesson model which calculates the total fee received:
def total_fee(self):
evaluations = self.evaluation_set.all()
total = 0;
for e in evaluations:
total += e.fee_paid
return total
However, I'm running the debug toolbar and this shows me that this view required 87 separate SQL queries when I ran it!
Obviously, I can't do that every time. How can I fetch all of the data in one go?
Any advice would be greatly appreciated.
Thanks.
I think I would personally tackle this one using Django's Aggregation functionality. It's hard for me to conceptualize your database structure without seeing your models, but I think the call would look something like this:
from django.db.models import Sum
total = self.evaluation_set.all().aggregate(total=Sum('fee_paid'))['total']
That should give you the sum of all the fees paid for everything in the evaluation set in 1 DB call, I think. Take that with a grain of salt as I haven't tested it.
Hope that helps.
精彩评论