Self hosted FLOSS fitness/workout, nutrition and weight tracker
Optimize ingredient queryset and sorting behavior
Roland Geider1b6f26670a22
diff --git a/wger/nutrition/api/filtersets.py b/wger/nutrition/api/filtersets.pyindex 843765fd8..4d86ad6fd 100644--- a/wger/nutrition/api/filtersets.py+++ b/wger/nutrition/api/filtersets.py@@ -87,7 +87,9 @@ class IngredientFilterSet(filters.FilterSet):.order_by('-similarity', 'name'))else:- return queryset.filter(name__icontains=value)+ # Explicit order_by('name') because the viewset strips Meta.ordering.+ # Search results are small, so sorting them is cheap.+ return queryset.filter(name__icontains=value).order_by('name')def search_languagecode(self, queryset, name, value):"""diff --git a/wger/nutrition/api/views.py b/wger/nutrition/api/views.pyindex 1c2304eeb..4275a4cfa 100644--- a/wger/nutrition/api/views.py+++ b/wger/nutrition/api/views.py@@ -71,10 +71,9 @@ class IngredientViewSet(viewsets.ReadOnlyModelViewSet):serializer_class = IngredientSerializerordering_fields = '__all__'filterset_class = IngredientFilterSet- queryset = Ingredient.objects.select_related(- 'language',- 'license',- ).prefetch_related('ingredientweightunit_set')++ # Strip default ordering ('name'), this makes the API/DB more performant+ queryset = Ingredient.objects.prefetch_related('ingredientweightunit_set').order_by()throttle_scope = 'ingredient_list'def get_throttles(self):@@ -88,10 +87,6 @@ class IngredientViewSet(viewsets.ReadOnlyModelViewSet):self.throttle_scope = 'ingredient_list' if self.action == 'list' else 'ingredient_detail'return super().get_throttles()- @method_decorator(cache_page(settings.WGER_SETTINGS['INGREDIENT_CACHE_TTL']))- def list(self, request, *args, **kwargs):- return super().list(request, *args, **kwargs)-@action(detail=True)def get_values(self, request, pk):"""@@ -148,10 +143,11 @@ class IngredientInfoViewSet(IngredientViewSet):def get_queryset(self):"""Optimize the queryset with select_related to avoid n+1 queries"""- return Ingredient.objects.select_related(- 'language',- 'license',- 'image',+ # See IngredientViewSet.queryset for the rationale behind .order_by().+ return (+ Ingredient.objects.select_related('language', 'license', 'image')+ .prefetch_related('ingredientweightunit_set')+ .order_by())@@ -179,7 +175,7 @@ class IngredientSyncViewSet(viewsets.ReadOnlyModelViewSet):'language','license','image',- )+ ).prefetch_related('ingredientweightunit_set')class ImageViewSet(viewsets.ReadOnlyModelViewSet):diff --git a/wger/nutrition/tests/test_ingredient.py b/wger/nutrition/tests/test_ingredient.pyindex 2c855e25b..5f4ad034c 100644--- a/wger/nutrition/tests/test_ingredient.py+++ b/wger/nutrition/tests/test_ingredient.py@@ -454,7 +454,7 @@ class IngredientApiTestCase(api_base_test.ApiBaseResourceTestCase):pk = 4resource = Ingredientprivate_resource = False- overview_cached = True+ overview_cached = Falsedata = {'language': 1, 'license': 2}