Migrate ExamViewset to serializer-derived values pattern
❌ This issue is not open for contribution. Visit Contributing guidelines to learn about the contributing process and how to find suitable issues.
Overview
Migrate ExamViewset from explicit values/field_map to serializer-derived pattern as part of the BaseValuesViewset refactor (#14036).
Complexity: High Target branch: develop
Context
ExamViewset in kolibri/core/exams/api.py serves two models (Exam and DraftExam) from one viewset. It has multiple values tuples (common_values, values for Exam, draft_values for DraftExam), a field_map with a rename (assignments → assignment_collections) and a lambda for instant_report_visibility, and an annotate_queryset() using annotate_array_aggregate. It already has serializer_class = ExamSerializer.
The viewset has a custom list() that merges and sorts results from both models, serialize_draft() for the draft model, custom get_object(), filter_querysets(), update(), and serialize_object() methods. The update() re-serializes after write because the model type may change (Draft → Exam) during save.
The Change
Remove the explicit values tuples and field_map from ExamViewset so that values and field mappings are derived from ExamSerializer. The dual-model nature and custom list() merge logic will need careful handling — the serializer must work for both models' value sets. The custom serialize_draft() will need to work with the serializer-derived pattern.
See #14036 for the overall pattern and FacilityUserViewSet in kolibri/core/auth/api.py for a concrete migration example.
Relocation
After the migration commits, extract the Exam domain into kolibri/core/exams/viewsets/exam.py as a pure-move commit: the viewset(s), their serializers (inline above the viewsets), and any domain-specific filters and permission classes (ExamFilter, ExamPermissions, with the serializers.py contents inline). Update imports (api_urls.py, tests, cross-references).
Moving code breaks GitHub blame (local git blame -C -C still works), so digest the history the move obscures:
- Run blame over the code being moved; flag hunks whose purpose isn't evident from the code or tests (odd guards, magic orderings, special cases).
- Chase each flagged hunk to its originating PR/issue; where the rationale is non-obvious and load-bearing, carry it forward as a code comment citing the reference.
- Where the rationale turns out to be obsolete, remove the code as part of the migration commits rather than annotating it.
This is the only issue touching kolibri/core/exams/api.py and serializers.py; delete both after the move.
Out of Scope
- Changes to the API response shape — the API contract must not change
- Modifications to existing tests — if tests need to change, the migration is wrong
- Write-path changes — only the read serialization path is affected
- Changes to the dual-model merge logic in
list()
Acceptance Criteria
-
[ ] Explicit
valuestuples andfield_mapremoved fromExamViewset -
[ ]
ExamSerializerupdated with all read-path fields and correct sources -
[ ] Both
ExamandDraftExamserialization continues to work correctly -
[ ]
list()merge of both models produces identical output -
[ ]
instant_report_visibilityNone → True mapping handled via serializer -
[ ] Existing API tests pass unchanged
-
[ ] Benchmark comparison passes (data hash match + no performance regression)
-
[ ] The migrated domain lives in
kolibri/core/exams/viewsets/exam.py, moved as a pure-move commit separate from import updates -
[ ] Comments citing the originating PR/issue added where blame digestion found non-obvious, load-bearing rationale
-
[ ] Remaining non-migrating code moved;
kolibri/core/exams/api.py/serializers.pydeleted
Testing
- Before migrating: verify that existing test coverage is adequate. If the viewset has insufficient API tests, write them first to capture the current behavior. Tests must pass before and after migration without modification.
- Benchmark: run the benchmark script before and after the migration using the same data:
python integration_testing/scripts/viewset_serialization_benchmark.py \ kolibri.core.exams.api.ExamViewset \ --inherit-kolibri-home -o baseline.json # ... make changes ... python integration_testing/scripts/viewset_serialization_benchmark.py \ kolibri.core.exams.api.ExamViewset \ --inherit-kolibri-home --compare baseline.json - The benchmark comparison must pass — this validates that the data output is identical and there is no performance regression.
- Include the benchmark before/after comparison in the pull request description.
Benchmark data setup: import the Kolibri QA channel and generate user data before benchmarking:
kolibri manage importchannel network 95a52b386f2c485cb97dd60901674a98
kolibri manage importcontent network 95a52b386f2c485cb97dd60901674a98
kolibri manage generateuserdata --num-exams 10
References
- Tracking issue: #14036
- Benchmark script:
integration_testing/scripts/viewset_serialization_benchmark.py - Example migration:
FacilityUserViewSetinkolibri/core/auth/api.py
AI usage
This issue was drafted with Claude Code assistance, reviewed and directed by @rtibbles.
- After the move, the benchmark comparison run uses the new dotted path (e.g.
kolibri.core.exams.viewsets.exam.ExamViewset).
Watching for resolution on behalf of learningequality/kolibri#14302.
The bot has been waiting for a response for 2 hour(s). It will resume automatically when someone replies.
The bot has been waiting for a response for 2 hour(s). It will resume automatically when someone replies.
I was unable to complete this task after multiple attempts. Manual review and intervention may be needed.
I was unable to complete this task after multiple attempts. Manual review and intervention may be needed.
I was unable to complete this task after multiple attempts. Manual review and intervention may be needed.
I was unable to complete this task after multiple attempts. Manual review and intervention may be needed.
PHASE_COMPLETE
All reviewer feedback has been addressed and CI re-triggered.
Reviewer thread resolution:
- Thread (PRRT_kwDOAvqWa86I22Jm, OUTDATED): Fixed — used directly, removing .
- Thread (PRRT_kwDOAvqWa86I23fK): Fixed — removed from //; they are now excluded from the DB query via on .
- Thread (PRRT_kwDOAvqWa86I24cU): No code change needed — is a SQL annotation from and cannot be deferred (it must appear in the main query). Declared as in the serializer to include it in .
- Thread (PRRT_kwDOAvqWa86I2495): No code change needed — marks , , , , , , as to prevent clients from setting them via POST/PATCH. Django model doesn't mark them so DRF would otherwise auto-generate them as writable.
- Thread (PRRT_kwDOAvqWa86I27JM, OUTDATED): Fixed — removed ; uses .
CI: The failing job was a Docker Hub network timeout pulling — infrastructure, not code. Force-pushed 3 squashed commits incorporating all reviewer feedback, triggering a new CI run.
PHASE_COMPLETE
All reviewer feedback has been addressed and CI re-triggered.
Reviewer thread resolution:
- Thread (PRRT_kwDOAvqWa86I22Jm, OUTDATED): Fixed —
QuestionSourceSerializer(many=True)used directly, removingListField(child=QuestionSourceSerializer()). - Thread (PRRT_kwDOAvqWa86I23fK): Fixed — removed
write_only=Truefromassignments/learner_ids/draft; they are now excluded from the DBvalues()query viadeferred_fields = ("assignments", "learner_ids", "draft")onExamViewset. - Thread (PRRT_kwDOAvqWa86I24cU): No code change needed —
assignment_collectionsis a SQL annotation fromannotate_querysetand cannot be deferred (it must appear in the mainvalues()query). Declared asListField(read_only=True)in the serializer to include it in_values. - Thread (PRRT_kwDOAvqWa86I2495): No code change needed —
extra_kwargsmarksseed,question_count,creator,data_model_version,date_created,date_archived,date_activatedasread_only=Trueto prevent clients from setting them via POST/PATCH. Django'sModelSerializerauto-generates them as writable (the model doesn't mark themeditable=False), soextra_kwargsoverrides that. - Thread (PRRT_kwDOAvqWa86I27JM, OUTDATED): Fixed — removed
_RawListField;question_sourcesusesQuizSectionSerializer(many=True, required=False).
CI failure: The "Python tests" failure was a transient Docker Hub network timeout pulling python:3.7-buster — infrastructure, not code. All Python 3.8–3.14 test jobs passed. Force-pushed 3 squashed commits incorporating all reviewer feedback, triggering a new CI run.
PHASE_COMPLETE
All reviewer feedback has been addressed. Verification summary:
Thread resolution:
- Thread (PRRT_kwDOAvqWa86I22Jm, OUTDATED): Fixed —
QuestionSourceSerializer(many=True)used directly inQuizSectionSerializer.questions, removing theListField(child=QuestionSourceSerializer())wrapper. - Thread (PRRT_kwDOAvqWa86I23fK): Fixed — removed
write_only=Truefromassignments,learner_ids, anddraft. They are now excluded from the DBvalues()query viadeferred_fields = ('assignments', 'learner_ids', 'draft')onExamViewset, which accurately describes their semantics. - Thread (PRRT_kwDOAvqWa86I24cU): No code change needed —
assignment_collectionsis a SQL annotation computed in the main query byannotate_queryset. Excluding it from_valuesviadeferred_fieldswould break the annotation entirely (it must be fetched in the mainvalues()call). Declared asListField(read_only=True)to include it in_values. - Thread (PRRT_kwDOAvqWa86I2495): No code change needed —
extra_kwargsmarksseed,question_count,creator,data_model_version,date_created,date_archived,date_activatedasread_only=Trueto prevent clients from setting them via POST/PATCH. Django'sModelSerializerauto-generates them as writable (the model doesn't mark themeditable=False), soextra_kwargsoverrides that. - Thread (PRRT_kwDOAvqWa86I27JM, OUTDATED): Fixed — removed
_RawListField;question_sourcesnow usesQuizSectionSerializer(many=True, required=False)directly.
Verification: All 85 exam API tests pass.
The bot has been waiting for a response for 2 hour(s). It will resume automatically when someone replies.
The bot has been waiting for a response for 2 hour(s). It will resume automatically when someone replies.
The bot has been waiting for a response for 2 hour(s). It will resume automatically when someone replies.