Skip to content

Commit cfb61e4

Browse files
committed
Optimize the exercise queryset
1 parent 881e071 commit cfb61e4

File tree

1 file changed

+30
-2
lines changed

1 file changed

+30
-2
lines changed

wger/exercises/api/views.py

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,10 @@
2020
# Django
2121
from django.conf import settings
2222
from django.contrib.postgres.search import TrigramSimilarity
23-
from django.db.models import Q
23+
from django.db.models import (
24+
Prefetch,
25+
Q,
26+
)
2427
from django.utils.decorators import method_decorator
2528
from django.utils.translation import gettext as _
2629
from django.views.decorators.cache import cache_page
@@ -328,7 +331,6 @@ class ExerciseInfoViewset(viewsets.ReadOnlyModelViewSet):
328331
is the recommended way to access the exercise data.
329332
"""
330333

331-
queryset = Exercise.objects.all()
332334
serializer_class = ExerciseInfoSerializer
333335
ordering_fields = '__all__'
334336
filterset_class = ExerciseFilterSet
@@ -343,6 +345,32 @@ class ExerciseInfoViewset(viewsets.ReadOnlyModelViewSet):
343345
'license_author',
344346
)
345347

348+
def get_queryset(self):
349+
"""
350+
Optimize the queryset with select_related and prefetch_related to avoid
351+
n+1 queries
352+
353+
One improvement is that we access the historical records of the exercise
354+
from the django-simple-history package, which are not really prefetchable
355+
since they are a manager.
356+
"""
357+
358+
return Exercise.objects.select_related(
359+
'category',
360+
'license',
361+
'variations',
362+
).prefetch_related(
363+
'muscles',
364+
'muscles_secondary',
365+
'equipment',
366+
'exerciseimage_set',
367+
'exercisevideo_set',
368+
Prefetch(
369+
'translations',
370+
queryset=Translation.objects.prefetch_related('alias_set', 'exercisecomment_set'),
371+
),
372+
)
373+
346374

347375
class ExerciseSubmissionViewSet(CreateAPIView):
348376
"""

0 commit comments

Comments
 (0)