Skip to content

Commit

Permalink
Fix the performance of the database query in the user_results tag
Browse files Browse the repository at this point in the history
The commit a6c1ea7 tried to optimize
the submitter statistics in the results page (Your points). However,
the database query in the `user_results` template tag was too slow
on courses with hundreds of students and thousands of submissions.

The order of `filter()` and `annotate()` affects the results, that is,
they are not commutative. The new version in this commit seems to
work correctly and performs quite well.

https://docs.djangoproject.com/en/3.2/topics/db/aggregation/#order-of-annotate-and-filter-clauses
  • Loading branch information
markkuriekkinen committed Feb 23, 2022
1 parent 8245ca6 commit 213e2a1
Showing 1 changed file with 1 addition and 1 deletion.
2 changes: 1 addition & 1 deletion exercise/templatetags/exercise.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,9 @@ def user_results(context: Context, student: Optional[User] = None) -> Dict[str,
instance = context['instance']
values['student_count'] = instance.students.count()
counts = (instance.students
.filter(submissions__exercise__course_module__course_instance=instance)
.values('submissions__exercise_id')
.annotate(count=models.Count('submissions__submitters', distinct=True))
.filter(submissions__exercise__course_module__course_instance=instance)
.order_by()
)
values['exercise_submitter_counts'] = {row['submissions__exercise_id']: row['count'] for row in counts}
Expand Down

0 comments on commit 213e2a1

Please sign in to comment.