Django - Get total of columns in generic list view
I am using a List view from a custom query set to display a list of records. One of the columns I am retrieving is a decimal field. I would like to get the total value of that column for all of the rows retrieved.
Presumably I need to do this within the get_context_data of the ListView class but I'm not sure about how to work it out. If I try and perform calculations on the queryset within this method, would I not end up performing the query twice?
My query doesn't fit entirely to my model schema and the field I want to perform the calculation on is itself calculated on a per-row basis.
return Lesson.objects.select_related().filter(user=self.request.user).extra(select={'total_fee' : 'SELECT SUM(fee_paid) FROM lessons_evaluation WHERE lessons_evaluation.lesson_id=lessons_lesson.id GROUP BY lessons_evaluation.lesson_id', 'desc' : 'SELECT CASE WHEN COUNT(lessons_evaluation.id) = 0 THEN "None Set" WHEN COUNT(lessons_evaluation.id) = 1 THEN GROUP_CONCAT(CONCAT(lessons_student.first_name, " ", lessons_student.last_name)) ELSE CONCAT(COUNT(lessons_evaluation.id), " students") END FROM lessons_evaluation, lessons_student WHERE lessons_evaluation.lesson_id=lessons_lesson.id AND lessons_evaluation.student_id = lessons_student.id GROUP BY lessons_eva开发者_开发技巧luation.lesson_id'})
EDIT:
Lesson has a many-to-many relationship twith Student through the intermediary Evaluation model.
Any advice appreciated.
Thanks.
I'd recommend using the aggregation feature to do this processing on the database server. Ideally, your webserver should be as light as possible, because your database server is a) optimized to do these types of operations, and b) more likely to have better hardware and thus faster computation times.
EDIT: This is likely to have two database hits, yes, but it's likely faster to do the computation on the database server than to iterate-and-sum over the queryset in python.
精彩评论