From 637416dd79ecdea536d0bb601b57de35e903d66e Mon Sep 17 00:00:00 2001 From: Ali Nawaz Date: Tue, 19 Sep 2023 12:07:49 +0500 Subject: [PATCH] perf: N+1 fixes --- course_discovery/apps/api/serializers.py | 15 +++++++++++++-- .../api/v1/tests/test_views/test_course_runs.py | 4 ++-- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/course_discovery/apps/api/serializers.py b/course_discovery/apps/api/serializers.py index f49ca15c18..70f3cbc457 100644 --- a/course_discovery/apps/api/serializers.py +++ b/course_discovery/apps/api/serializers.py @@ -1023,10 +1023,17 @@ class CourseRunSerializer(MinimalCourseRunSerializer): def prefetch_queryset(cls, queryset=None): queryset = super().prefetch_queryset(queryset=queryset) - return queryset.select_related('language', 'video', 'expected_program_type').prefetch_related( + return queryset.select_related( 'course__level_type', + 'course__video__image', + 'language', + 'video', + 'expected_program_type' + ).prefetch_related( + 'course__level_type__translations', 'transcript_languages', 'video__image', + 'language__translations', Prefetch('staff', queryset=MinimalPersonSerializer.prefetch_queryset()), ) @@ -1100,7 +1107,11 @@ class CourseRunWithProgramsSerializer(CourseRunSerializer): def prefetch_queryset(cls, queryset=None): queryset = super().prefetch_queryset(queryset=queryset) - return queryset.prefetch_related('course__programs__excluded_course_runs') + return queryset.select_related('course').prefetch_related( + Prefetch('course__programs', queryset=( + Program.objects.select_related('type', 'partner').prefetch_related('excluded_course_runs', 'courses') + )) + ) def get_programs(self, obj): programs = [] diff --git a/course_discovery/apps/api/v1/tests/test_views/test_course_runs.py b/course_discovery/apps/api/v1/tests/test_views/test_course_runs.py index 965ea3bf44..a541ebed46 100644 --- a/course_discovery/apps/api/v1/tests/test_views/test_course_runs.py +++ b/course_discovery/apps/api/v1/tests/test_views/test_course_runs.py @@ -1019,7 +1019,7 @@ def test_list(self): """ Verify the endpoint returns a list of all course runs. """ url = reverse('api:v1:course_run-list') - with self.assertNumQueries(17, threshold=3): + with self.assertNumQueries(14, threshold=3): response = self.client.get(url) assert response.status_code == 200 @@ -1032,7 +1032,7 @@ def test_list_sorted_by_course_start_date(self): """ Verify the endpoint returns a list of all course runs sorted by start date. """ url = '{root}?ordering=start'.format(root=reverse('api:v1:course_run-list')) - with self.assertNumQueries(17, threshold=3): + with self.assertNumQueries(14, threshold=3): response = self.client.get(url) assert response.status_code == 200