Self hosted FLOSS fitness/workout, nutrition and weight tracker
feat: implement exercise search with alias-aware, language-scoped matching. Wire ExerciseFilterSet into ExerciseInfoViewset and add tests similar to ingredient search while keeping the legacy search endpoint for compatibility
Christián Feliks0f78285ab581
diff --git a/wger/exercises/api/filtersets.py b/wger/exercises/api/filtersets.pynew file mode 100644index 000000000..028da4295--- /dev/null+++ b/wger/exercises/api/filtersets.py@@ -0,0 +1,91 @@+# This file is part of wger Workout Manager.+#+# wger Workout Manager is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published by+# the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# wger Workout Manager is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU Affero General Public License+# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.+++# Django+from django.contrib.postgres.search import TrigramSimilarity+from django.db.models import (+ Exists,+ OuterRef,+ Q,+)++# Third Party+from django_filters import rest_framework as filters++# wger+from wger.exercises.models import (+ Exercise,+ Translation,+)+from wger.utils.db import is_postgres_db+from wger.utils.language import load_language+++class ExerciseFilterSet(filters.FilterSet):+ """+ Filters for the regular exercises endpoints to support fulltext name search+ and language filtering, similar to IngredientFilterSet.+ """++ name__search = filters.CharFilter(method='search_name_fulltext')+ language__code = filters.CharFilter(method='search_languagecode')++ def search_name_fulltext(self, queryset, name, value):+ if not value:+ return queryset++ languages_param = self.data.get('language__code')+ languages = None+ if languages_param:+ languages = [load_language(code) for code in set(languages_param.split(','))]++ if is_postgres_db():+ translation_subquery = Translation.objects.filter(exercise=OuterRef('pk'))+ if languages:+ translation_subquery = translation_subquery.filter(language__in=languages)+ translation_subquery = translation_subquery.annotate(+ similarity=TrigramSimilarity('name', value)+ ).filter(Q(similarity__gt=0.15) | Q(alias__alias__icontains=value))++ qs = queryset.filter(Exists(translation_subquery))+ else:+ translation_subquery = Translation.objects.filter(exercise=OuterRef('pk')).filter(+ Q(name__icontains=value) | Q(alias__alias__icontains=value)+ )+ if languages:+ translation_subquery = translation_subquery.filter(language__in=languages)+ qs = queryset.filter(Exists(translation_subquery))++ return qs.distinct()++ def search_languagecode(self, queryset, name, value):+ if not value:+ return queryset+ languages = [load_language(code) for code in set(value.split(','))]+ if not languages:+ return queryset+ return queryset.filter(translations__language__in=languages).distinct()++ class Meta:+ model = Exercise+ fields = {+ 'id': ['exact', 'in'],+ 'uuid': ['exact'],+ 'category': ['exact', 'in'],+ 'muscles': ['exact', 'in'],+ 'muscles_secondary': ['exact', 'in'],+ 'equipment': ['exact', 'in'],+ }diff --git a/wger/exercises/api/views.py b/wger/exercises/api/views.pyindex 2752dd4c2..f6ba04e0b 100644--- a/wger/exercises/api/views.py+++ b/wger/exercises/api/views.py@@ -52,6 +52,7 @@ from rest_framework.response import Responsefrom rest_framework.viewsets import ModelViewSet# wger+from wger.exercises.api.filtersets import ExerciseFilterSetfrom wger.exercises.api.permissions import CanContributeExercisesfrom wger.exercises.api.serializers import (DeletionLogSerializer,@@ -330,6 +331,7 @@ class ExerciseInfoViewset(viewsets.ReadOnlyModelViewSet):queryset = Exercise.objects.all()serializer_class = ExerciseInfoSerializerordering_fields = '__all__'+ filterset_class = ExerciseFilterSetfilterset_fields = ('uuid','category',diff --git a/wger/exercises/tests/api/test_exercise_info_search_api.py b/wger/exercises/tests/api/test_exercise_info_search_api.pynew file mode 100644index 000000000..078a289ba--- /dev/null+++ b/wger/exercises/tests/api/test_exercise_info_search_api.py@@ -0,0 +1,129 @@+# This file is part of wger Workout Manager.+#+# wger Workout Manager is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published by+# the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# wger Workout Manager is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU Affero General Public License+# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.++# Third Party+from rest_framework import status++# wger+from wger.core.tests.api_base_test import ApiBaseTestCase+from wger.core.tests.base_testcase import BaseTestCase+++class ExerciseInfoFilterApiTestCase(BaseTestCase, ApiBaseTestCase):+ url = '/api/v2/exerciseinfo/'++ def setUp(self):+ super().setUp()+ self.init_media_root()++ def _results(self, response):+ if isinstance(response.data, dict) and 'results' in response.data:+ return response.data['results']+ return response.data++ def _has_translation_name(self, item, expected_name: str) -> bool:+ for t in item.get('translations', []):+ if t.get('name') == expected_name:+ return True+ return False++ def test_basic_search_logged_out(self):+ """+ Logged-out users can search via name__search and language__code+ """+ response = self.client.get(self.url + '?name__search=exercise&language__code=en')+ results = self._results(response)+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(len(results), 4)+ ids = {item['id'] for item in results}+ self.assertIn(1, ids)+ item1 = next(item for item in results if item['id'] == 1)+ self.assertTrue(self._has_translation_name(item1, 'An exercise'))++ def test_basic_search_logged_in(self):+ """+ Logged-in users get the same results+ """+ self.authenticate('test')+ response = self.client.get(self.url + '?name__search=exercise&language__code=en')+ results = self._results(response)++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(len(results), 4)+ ids = {item['id'] for item in results}+ self.assertIn(1, ids)+ item1 = next(item for item in results if item['id'] == 1)+ self.assertTrue(self._has_translation_name(item1, 'An exercise'))++ def test_search_language_code_en_no_results(self):+ """+ A DE-only exercise name should not be found when searching in English+ """+ response = self.client.get(self.url + '?name__search=Weitere&language__code=en')+ results = self._results(response)++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(len(results), 0)++ def test_search_language_code_de(self):+ """+ A DE-only exercise should be found when searching in German+ """+ response = self.client.get(self.url + '?name__search=Weitere&language__code=de')+ results = self._results(response)++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(len(results), 1)+ self.assertEqual(results[0]['id'], 4)++ def test_search_several_language_codes(self):+ """+ Passing different language codes works correctly+ """+ response = self.client.get(self.url + '?name__search=demo&language__code=en,de')+ results = self._results(response)++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(len(results), 4)++ def test_search_unknown_language_codes(self):+ """+ Unknown language codes are ignored+ """+ response = self.client.get(self.url + '?name__search=demo&language__code=en,de,zz')+ results = self._results(response)++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(len(results), 4)++ def test_search_all_languages(self):+ """+ Disable all language filters when language__code is omitted+ """+ response = self.client.get(self.url + '?name__search=demo')+ results = self._results(response)++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(len(results), 4)++ def test_search_matches_alias(self):+ """+ Alias terms should also match+ """+ response = self.client.get(self.url + '?name__search=different&language__code=en')+ results = self._results(response)++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(len(results), 1)