Self hosted FLOSS fitness/workout, nutrition and weight tracker
Optimize the exercise queryset
Roland Geidercfb61e4cd582
diff --git a/wger/exercises/api/views.py b/wger/exercises/api/views.pyindex f6ba04e0b..5739904b3 100644--- a/wger/exercises/api/views.py+++ b/wger/exercises/api/views.py@@ -20,7 +20,10 @@ from uuid import UUID# Djangofrom django.conf import settingsfrom django.contrib.postgres.search import TrigramSimilarity-from django.db.models import Q+from django.db.models import (+ Prefetch,+ Q,+)from django.utils.decorators import method_decoratorfrom django.utils.translation import gettext as _from django.views.decorators.cache import cache_page@@ -328,7 +331,6 @@ class ExerciseInfoViewset(viewsets.ReadOnlyModelViewSet):is the recommended way to access the exercise data."""- queryset = Exercise.objects.all()serializer_class = ExerciseInfoSerializerordering_fields = '__all__'filterset_class = ExerciseFilterSet@@ -343,6 +345,32 @@ class ExerciseInfoViewset(viewsets.ReadOnlyModelViewSet):'license_author',)+ def get_queryset(self):+ """+ Optimize the queryset with select_related and prefetch_related to avoid+ n+1 queries++ One improvement is that we access the historical records of the exercise+ from the django-simple-history package, which are not really prefetchable+ since they are a manager.+ """++ return Exercise.objects.select_related(+ 'category',+ 'license',+ 'variations',+ ).prefetch_related(+ 'muscles',+ 'muscles_secondary',+ 'equipment',+ 'exerciseimage_set',+ 'exercisevideo_set',+ Prefetch(+ 'translations',+ queryset=Translation.objects.prefetch_related('alias_set', 'exercisecomment_set'),+ ),+ )+class ExerciseSubmissionViewSet(CreateAPIView):"""