Self hosted FLOSS fitness/workout, nutrition and weight tracker
Add unique constraint to the exercise translations
Roland Geider59397799ba59
diff --git a/wger/exercises/management/commands/exercises-health-check.py b/wger/exercises/management/commands/exercises-health-check.pyindex 8c0b36b29..cc7440377 100644--- a/wger/exercises/management/commands/exercises-health-check.py+++ b/wger/exercises/management/commands/exercises-health-check.py@@ -56,15 +56,6 @@ class Command(BaseCommand):'accessed over the UI)',)- parser.add_argument(- '--delete-duplicate-translations',- action='store_true',- dest='delete_duplicates',- default=False,- help='Delete duplicate translations (e.g. if an exercise has two French entries, '- 'the first one will be removed)',- )-parser.add_argument('--delete-no-english',action='store_true',@@ -83,64 +74,33 @@ class Command(BaseCommand):def handle(self, **options):delete_untranslated = options['delete_untranslated'] or options['delete_all']- delete_duplicates = options['delete_duplicates'] or options['delete_all']delete_no_english = options['delete_no_english'] or options['delete_all']self.english = Language.objects.get(short_name=ENGLISH_SHORT_NAME)- for base in Exercise.objects.all():- self.handle_untranslated(base, delete_untranslated)- self.handle_no_english(base, delete_no_english)- self.handle_duplicate_translations(base, delete_duplicates)+ for exercise in Exercise.objects.all():+ self.handle_untranslated(exercise, delete_untranslated)+ self.handle_no_english(exercise, delete_no_english)- def handle_untranslated(self, base: Exercise, delete: bool):+ def handle_untranslated(self, exercise: Exercise, delete: bool):"""Delete exercises without translations"""- if not base.pk or base.translations.count():+ if not exercise.pk or exercise.translations.count():return- self.stdout.write(self.style.WARNING(f'Exercise {base.uuid} has no translations!'))+ self.stdout.write(self.style.WARNING(f'Exercise {exercise.uuid} has no translations!'))if delete:- base.delete()+ exercise.delete()self.stdout.write(' -> deleted')- def handle_no_english(self, base: Exercise, delete: bool):- if not base.pk or base.translations.filter(language=self.english).exists():+ def handle_no_english(self, exercise: Exercise, delete: bool):+ if not exercise.pk or exercise.translations.filter(language=self.english).exists():return- self.stdout.write(self.style.WARNING(f'Exercise {base.uuid} has no English translation!'))+ self.stdout.write(+ self.style.WARNING(f'Exercise {exercise.uuid} has no English translation!')+ )if delete:- base.delete()+ exercise.delete()self.stdout.write(' -> deleted')-- def handle_duplicate_translations(self, base: Exercise, delete: bool):- if not base.pk:- return-- exercise_languages = base.translations.values_list('language', flat=True)- duplicates = [- Language.objects.get(pk=item)- for item, count in collections.Counter(exercise_languages).items()- if count > 1- ]-- if not duplicates:- return-- warning = f'Exercise {base.uuid} has duplicate translations!'- self.stdout.write(self.style.WARNING(warning))-- # Output the duplicates- for language in duplicates:- translations = base.translations.filter(language=language)- self.stdout.write(f'language {language.short_name}:')- for translation in translations:- self.stdout.write(f' * {translation.name} {translation.uuid}')- self.stdout.write('')-- # And delete them- if delete:- self.stdout.write(f' Deleting all but first {language.short_name} translation')- for translation in translations[1:]:- translation.delete()diff --git a/wger/exercises/migrations/0033_uniqueness_constraint_translations.py b/wger/exercises/migrations/0033_uniqueness_constraint_translations.pynew file mode 100644index 000000000..754a55af2--- /dev/null+++ b/wger/exercises/migrations/0033_uniqueness_constraint_translations.py@@ -0,0 +1,20 @@+# Generated by Django 5.2.7 on 2025-10-03 19:12++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ('exercises', '0032_rename_exercise'),+ ]++ operations = [+ migrations.AddConstraint(+ model_name='translation',+ constraint=models.UniqueConstraint(+ fields=('exercise', 'language'),+ name='unique_exercise_language_translation',+ violation_error_message='A translation for this exercise and language already exists.',+ ),+ ),+ ]diff --git a/wger/exercises/models/translation.py b/wger/exercises/models/translation.pyindex fc133d9c4..97efbd1da 100644--- a/wger/exercises/models/translation.py+++ b/wger/exercises/models/translation.py@@ -105,6 +105,13 @@ class Translation(AbstractLicenseModel, AbstractHistoryMixin, models.Model):'name',]indexes = (GinIndex(fields=['name']),)+ constraints = [+ models.UniqueConstraint(+ fields=['exercise', 'language'],+ name='unique_exercise_language_translation',+ violation_error_message='A translation for this exercise and language already exists.',+ )+ ]def get_absolute_url(self):"""diff --git a/wger/exercises/tests/test_exercise_translation.py b/wger/exercises/tests/test_exercise_translation.pyindex b5f412962..e7c70ab07 100644--- a/wger/exercises/tests/test_exercise_translation.py+++ b/wger/exercises/tests/test_exercise_translation.py@@ -30,7 +30,10 @@ from wger.exercises.models import (Muscle,Translation,)-from wger.utils.constants import CC_BY_SA_4_LICENSE_ID+from wger.utils.constants import (+ CC_0_LICENSE_ID,+ CC_BY_SA_4_LICENSE_ID,+)class ExerciseRepresentationTestCase(WgerTestCase):@@ -161,7 +164,7 @@ class ExerciseTranslationCustomApiTestCase(ExerciseCrudApiTestCase):'name': 'A new name','description': 'The wild boar is a suid native to much of Eurasia and North Africa','language': 1,- 'exercise': 2,+ 'exercise': 1,}def get_resource_name(self):@@ -172,6 +175,7 @@ class ExerciseTranslationCustomApiTestCase(ExerciseCrudApiTestCase):Test that it is not possible to change the exercise id of an existingtranslation."""+ Translation.objects.filter(exercise_id=2).delete()translation = Translation.objects.get(pk=self.pk)self.assertEqual(translation.exercise_id, 1)@@ -217,7 +221,7 @@ class ExerciseTranslationCustomApiTestCase(ExerciseCrudApiTestCase):Test that it is not possible to set the license for a newly createdexercise translation (the license is always set to the default)"""- self.data['license'] = 3+ self.data['license'] = CC_0_LICENSE_IDself.authenticate('trainer1')response = self.client.post(self.url, data=self.data)@@ -241,7 +245,7 @@ class ExerciseTranslationCustomApiTestCase(ExerciseCrudApiTestCase):def test_post_only_one_language_per_base(self):"""Test that it's not possible to add a second translation for the same- base in the same language.+ exercise in the same language."""self.authenticate('trainer1')response = self.client.post(self.url, data=self.data)diff --git a/wger/exercises/tests/test_management_commands.py b/wger/exercises/tests/test_management_commands.pyindex 3f44d3946..ff252eb15 100644--- a/wger/exercises/tests/test_management_commands.py+++ b/wger/exercises/tests/test_management_commands.py@@ -115,24 +115,3 @@ class TestHealthCheckManagementCommands(WgerTestCase):call_command('exercises-health-check', '--delete-no-english', stdout=self.out)self.assertIn('-> deleted', self.out.getvalue())self.assertRaises(Exercise.DoesNotExist, Exercise.objects.get, pk=1)-- def test_find_duplicate_translations(self):- exercise = Translation.objects.get(pk=1)- exercise.language_id = 3- exercise.save()-- call_command('exercises-health-check', stdout=self.out)- self.assertIn(- 'Exercise acad3949-36fb-4481-9a72-be2ddae2bc05 has duplicate translations!',- self.out.getvalue(),- )- self.assertNotIn('-> deleted', self.out.getvalue())-- def test_fix_duplicate_translations(self):- exercise = Translation.objects.get(pk=1)- exercise.language_id = 3- exercise.save()-- call_command('exercises-health-check', '--delete-duplicate-translations', stdout=self.out)- self.assertIn('Deleting all but first fr translation', self.out.getvalue())- self.assertRaises(Translation.DoesNotExist, Translation.objects.get, pk=5)