Optimize exam collection queries by annotating exam counts and prefetching authors to improve template performance
This commit is contained in:
+25
-1
@@ -67,7 +67,7 @@ from generic.mixins import CheckCanEditMixin, SuperuserRequiredMixin
|
||||
|
||||
import zipfile
|
||||
from django.core.files.base import ContentFile
|
||||
from django.db.models import Q
|
||||
from django.db.models import Q, Count, F
|
||||
|
||||
from .forms import (
|
||||
CidGroupExamForm,
|
||||
@@ -4777,6 +4777,30 @@ class SupervisorList(CidManagerRequiredMixin, SingleTableMixin, FilterView):
|
||||
|
||||
class ExamCollectionList(ListView):
|
||||
model = ExamCollection
|
||||
|
||||
def get_queryset(self):
|
||||
"""Annotate exam counts per collection and prefetch authors to avoid N+1 queries in templates."""
|
||||
qs = (
|
||||
ExamCollection.objects.all()
|
||||
.annotate(
|
||||
anatomy_count=Count("anatomy_exams", filter=Q(anatomy_exams__archive=False)),
|
||||
longs_count=Count("longs_exams", filter=Q(longs_exams__archive=False)),
|
||||
physics_count=Count("physics_exams", filter=Q(physics_exams__archive=False)),
|
||||
rapids_count=Count("rapids_exams", filter=Q(rapids_exams__archive=False)),
|
||||
sbas_count=Count("sbas_exams", filter=Q(sbas_exams__archive=False)),
|
||||
)
|
||||
.annotate(
|
||||
total_count=F("anatomy_count")
|
||||
+F("longs_count")
|
||||
+F("physics_count")
|
||||
+F("rapids_count")
|
||||
+F("sbas_count")
|
||||
)
|
||||
.prefetch_related("author")
|
||||
.order_by("name")
|
||||
)
|
||||
|
||||
return qs
|
||||
|
||||
|
||||
class ExamCollectionDetail(DetailView, AuthorRequiredMixin):
|
||||
|
||||
Reference in New Issue
Block a user