Optimize CID lookups to reduce N+1 query pattern in exam review question responses

This commit is contained in:
Ross
2025-11-10 11:07:56 +00:00
parent fdc60bf2e9
commit b467407e19
+11 -2
View File
@@ -287,6 +287,15 @@ def exam_review_question_responses(request, pk: int, q_index: int):
# candidate try to resolve the CidUser and show CID + name if available. If neither
# is present fall back to empty/anonymous.
# Optimize CID lookups: collect distinct CID values and fetch all CidUser rows
# in a single query to avoid an N+1 query pattern.
cids_qs = exam_user_answers_qs.values_list("cid", flat=True).distinct()
cids = [c for c in cids_qs if c is not None and str(c).strip() != ""]
cid_map = {}
if cids:
for cu in CidUser.objects.filter(cid__in=cids):
cid_map[cu.cid] = cu
exam_user_answers = []
for ua in exam_user_answers_qs:
# default display
@@ -302,9 +311,9 @@ def exam_review_question_responses(request, pk: int, q_index: int):
else:
name = getattr(user, "username", str(user))
display = name
elif getattr(ua, "cid", None):
elif getattr(ua, "cid", None) is not None:
cid_val = ua.cid
cu = CidUser.objects.filter(cid=cid_val).first()
cu = cid_map.get(cid_val)
if cu is not None and cu.name:
display = f"CID{cid_val} ({cu.name})"
else: