Skip to content

Commit

Permalink
perf: N+1 fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
zawan-ila committed Sep 20, 2023
1 parent e279ca3 commit 637416d
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
15 changes: 13 additions & 2 deletions course_discovery/apps/api/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()),
)

Expand Down Expand Up @@ -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 = []
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down

0 comments on commit 637416d

Please sign in to comment.