File tree Expand file tree Collapse file tree 1 file changed +30
-2
lines changed Expand file tree Collapse file tree 1 file changed +30
-2
lines changed Original file line number Diff line number Diff line change 2020# Django
2121from django .conf import settings
2222from django .contrib .postgres .search import TrigramSimilarity
23- from django .db .models import Q
23+ from django .db .models import (
24+ Prefetch ,
25+ Q ,
26+ )
2427from django .utils .decorators import method_decorator
2528from django .utils .translation import gettext as _
2629from 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
347375class ExerciseSubmissionViewSet (CreateAPIView ):
348376 """
You can’t perform that action at this time.
0 commit comments