Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Cap the result count of filtered ingredient queries

Roland Geider2601ee2ce30d
diff --git a/wger/nutrition/api/views.py b/wger/nutrition/api/views.py
index 94584d851..75848238d 100644
--- a/wger/nutrition/api/views.py
+++ b/wger/nutrition/api/views.py
@@ -63,7 +63,10 @@ from wger.nutrition.models import (
MealItem,
NutritionPlan,
)
-from wger.utils.pagination import IngredientCursorPagination
+from wger.utils.pagination import (
+ IngredientCursorPagination,
+ IngredientLimitOffsetPagination,
+)
from wger.utils.viewsets import WgerOwnerObjectModelViewSet
@@ -92,6 +95,7 @@ class IngredientViewSet(viewsets.ReadOnlyModelViewSet):
# Strip default ordering ('name'), this makes the API/DB more performant
queryset = Ingredient.objects.prefetch_related('ingredientweightunit_set').order_by()
+ pagination_class = IngredientLimitOffsetPagination
throttle_scope = 'ingredient_list'
def get_throttles(self):
diff --git a/wger/utils/pagination.py b/wger/utils/pagination.py
index 7b990c4bf..5b290149f 100644
--- a/wger/utils/pagination.py
+++ b/wger/utils/pagination.py
@@ -29,6 +29,24 @@ class WgerLimitOffsetPagination(LimitOffsetPagination):
max_limit = 999
+class IngredientLimitOffsetPagination(WgerLimitOffsetPagination):
+ """
+ Reports at most ``count_cap`` results for a filtered list, so clients also
+ cannot page past it. Counting every match runs the search filter a second
+ time, which on the multi-million row table dominates the response time.
+ """
+
+ count_cap = 1000
+
+ def get_count(self, queryset):
+ # Mirrors ApproximateCountQuerySet.count(): no WHERE means no filter
+ if not getattr(queryset, 'query', None) or not queryset.query.where:
+ return super().get_count(queryset)
+
+ # Without the ordering the database can stop at the first count_cap rows
+ return super().get_count(queryset.order_by().values('pk')[: self.count_cap])
+
+
class IngredientCursorPagination(CursorPagination):
"""
Cursor-based pagination for ingredient sync.