Self hosted FLOSS fitness/workout, nutrition and weight tracker
Give the ingredient search a stable order
Roland Geider2ad8784ddd49
diff --git a/wger/nutrition/api/filtersets.py b/wger/nutrition/api/filtersets.pyindex 34d41fbe1..bbf157a0c 100644--- a/wger/nutrition/api/filtersets.py+++ b/wger/nutrition/api/filtersets.py@@ -124,8 +124,10 @@ class IngredientFilterSet(filters.FilterSet):# substring patterns. Exact matching still supports valid short names.if len(value) < 3:exact = PostgresILikeExact(F('name'), value)- return queryset.filter(exact).order_by('name')+ return queryset.filter(exact).order_by('name', 'id')+ # 'id' breaks ties: names repeat thousands of times, and tied rows+ # come back in any order, so LIMIT picks a different subset each timeexact = PostgresILikeExact(F('name'), value)starts_with = PostgresILikeStartsWith(F('name'), value)contains = PostgresILikeContains(F('name'), value)@@ -151,12 +153,12 @@ class IngredientFilterSet(filters.FilterSet):output_field=IntegerField(),),)- .order_by('-match_rank', '-similarity', 'name')+ .order_by('-match_rank', '-similarity', 'name', 'id'))else:# 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')+ return queryset.filter(name__icontains=value).order_by('name', 'id')def search_languagecode(self, queryset, name, value):"""diff --git a/wger/nutrition/tests/test_search_api.py b/wger/nutrition/tests/test_search_api.pyindex f32e7b44c..7ee2ea888 100644--- a/wger/nutrition/tests/test_search_api.py+++ b/wger/nutrition/tests/test_search_api.py@@ -26,13 +26,27 @@ from rest_framework import status# wgerfrom wger.core.tests.api_base_test import ApiBaseTestCasefrom wger.core.tests.base_testcase import BaseTestCase-from wger.nutrition.api.filtersets import _has_literal_trigram+from wger.nutrition.api.filtersets import (+ IngredientFilterSet,+ _has_literal_trigram,+)from wger.nutrition.models import Ingredientclass SearchIngredientApiTestCase(BaseTestCase, ApiBaseTestCase):url = '/api/v2/ingredient/'+ def test_search_ordering_ends_in_a_unique_tiebreaker(self):+ """Names repeat, so without a unique key LIMIT returns a random subset."""+ for term in ('test', 'ab'):+ with self.subTest(term=term):+ filterset = IngredientFilterSet(+ {'name__search': term},+ queryset=Ingredient.objects.all(),+ )++ self.assertEqual(filterset.qs.query.order_by[-1], 'id')+def test_basic_search_logged_out(self):"""Logged-out users are also allowed to use the search