Move the exercise variation to a field in the exercise table

This makes it now trivial to sync them to local instances
This commit is contained in:
Roland Geider
2026-04-13 11:58:59 +02:00
parent e5bc2d2c92
commit e5e2bda624
22 changed files with 1255 additions and 1897 deletions

View File

@@ -24,3 +24,7 @@ timer or similar. The `setting-repetitionunit` endpoint now exposes the new fiel
<https://github.com/wger-project/wger/issues/2124>
Automatically read the date from uploaded image to the gallery.
Move the variation ID from an (empty) table to a field in the exercise model. This
simplifies a lot of code and allows us to properly sync them to local instances
as well. The API endpoint `/api/v2/variations/` API endpoint has been removed.

View File

@@ -88,5 +88,5 @@ class ExerciseFilterSet(filters.FilterSet):
'muscles': ['exact', 'in'],
'muscles_secondary': ['exact', 'in'],
'equipment': ['exact', 'in'],
'variations': ['exact', 'in'],
'variation_group': ['exact', 'in'],
}

View File

@@ -14,6 +14,7 @@
# Standard Library
import logging
import uuid
# Django
from django.conf import settings
@@ -41,7 +42,6 @@ from wger.exercises.models import (
ExerciseVideo,
Muscle,
Translation,
Variation,
)
from wger.utils.cache import CacheKeyMapper
from wger.utils.constants import CC_BY_SA_4_LICENSE_ID
@@ -66,7 +66,7 @@ class ExerciseSerializer(serializers.ModelSerializer):
'muscles',
'muscles_secondary',
'equipment',
'variations',
'variation_group',
'license_author',
)
@@ -297,16 +297,6 @@ class ExerciseAliasSubmissionSerializer(serializers.ModelSerializer):
return alias
class ExerciseVariationSerializer(serializers.ModelSerializer):
"""
Exercise variation serializer
"""
class Meta:
model = Variation
fields = ('id', 'uuid')
class ExerciseInfoAliasSerializer(serializers.ModelSerializer):
"""
Exercise alias serializer for info endpoint
@@ -556,7 +546,6 @@ class ExerciseInfoSerializer(serializers.ModelSerializer):
equipment = EquipmentSerializer(many=True, read_only=True)
translations = ExerciseTranslationBaseInfoSerializer(many=True, read_only=True)
videos = ExerciseVideoInfoSerializer(source='exercisevideo_set', many=True, read_only=True)
variations = serializers.SlugRelatedField(slug_field='uuid', read_only=True)
author_history = serializers.ListSerializer(child=serializers.CharField())
total_authors_history = serializers.ListSerializer(child=serializers.CharField())
last_update_global = serializers.DateTimeField(read_only=True)
@@ -578,7 +567,7 @@ class ExerciseInfoSerializer(serializers.ModelSerializer):
'license_author',
'images',
'translations',
'variations',
'variation_group',
'images',
'videos',
'author_history',
@@ -636,8 +625,7 @@ class ExerciseSubmissionSerializer(serializers.ModelSerializer):
# Note, using a function here because of problems during tests
default=get_default_license,
)
variations = serializers.PrimaryKeyRelatedField(
queryset=Variation.objects.all(),
variation_group = serializers.UUIDField(
required=False,
allow_null=True,
)
@@ -656,7 +644,7 @@ class ExerciseSubmissionSerializer(serializers.ModelSerializer):
'muscles',
'muscles_secondary',
'equipment',
'variations',
'variation_group',
'variations_connect_to',
'license',
'license_author',
@@ -678,11 +666,11 @@ class ExerciseSubmissionSerializer(serializers.ModelSerializer):
{'translations': 'You must provide at least one translation in English.'}
)
# Either the variations or variations_connect_to field may be set, not both
if data.get('variations') and data.get('variations_connect_to'):
# Either variation_group or variations_connect_to may be set, not both
if data.get('variation_group') and data.get('variations_connect_to'):
raise serializers.ValidationError(
{
'variations': 'Either set the variations or the variations_connect_to field, not both.'
'variation_group': 'Either set variation_group or variations_connect_to, not both.'
}
)
@@ -695,7 +683,7 @@ class ExerciseSubmissionSerializer(serializers.ModelSerializer):
category=validated_data.pop('category'),
license=validated_data.pop('license'),
license_author=validated_data.pop('license_author'),
variations=validated_data.pop('variations', None),
variation_group=validated_data.pop('variation_group', None),
)
exercise.muscles.set(validated_data.pop('muscles'))
exercise.muscles_secondary.set(validated_data.pop('muscles_secondary'))
@@ -706,15 +694,15 @@ class ExerciseSubmissionSerializer(serializers.ModelSerializer):
serializer: ExerciseTranslationSubmissionSerializer = self.fields['translations'].child
serializer.create(validated_data=translation, exercise=exercise)
# If requested, add the exercise to an existing variation set
# If requested, create a new variation group for both exercises
connect_to: Exercise | None = validated_data.get('variations_connect_to')
if connect_to:
new_variation = Variation.objects.create()
new_group = uuid.uuid4()
connect_to.variations = new_variation
connect_to.variation_group = new_group
connect_to.save()
exercise.variations = new_variation
exercise.variation_group = new_group
exercise.save()
return exercise

View File

@@ -68,7 +68,6 @@ from wger.exercises.api.serializers import (
ExerciseSerializer,
ExerciseSubmissionSerializer,
ExerciseTranslationSerializer,
ExerciseVariationSerializer,
ExerciseVideoSerializer,
MuscleSerializer,
)
@@ -83,7 +82,6 @@ from wger.exercises.models import (
ExerciseVideo,
Muscle,
Translation,
Variation,
)
from wger.exercises.views.helper import StreamVerbs
from wger.utils.constants import (
@@ -345,7 +343,7 @@ class ExerciseInfoViewset(viewsets.ReadOnlyModelViewSet):
'muscles',
'muscles_secondary',
'equipment',
'variations',
'variation_group',
'license',
'license_author',
)
@@ -363,7 +361,6 @@ class ExerciseInfoViewset(viewsets.ReadOnlyModelViewSet):
return Exercise.objects.select_related(
'category',
'license',
'variations',
).prefetch_related(
'muscles',
'muscles_secondary',
@@ -610,16 +607,6 @@ class ExerciseAliasViewSet(ModelViewSet):
)
class ExerciseVariationViewSet(ModelViewSet):
"""
API endpoint for exercise variation objects
"""
serializer_class = ExerciseVariationSerializer
queryset = Variation.objects.all()
permission_classes = (CanContributeExercises,)
class MuscleViewSet(viewsets.ReadOnlyModelViewSet):
"""
API endpoint for muscle objects

File diff suppressed because it is too large Load Diff

View File

@@ -1,18 +1,4 @@
[
{
"pk": 1,
"model": "exercises.variation",
"fields": {
"uuid": "a1b2c3d4-0001-0000-0000-000000000001"
}
},
{
"pk": 2,
"model": "exercises.variation",
"fields": {
"uuid": "a1b2c3d4-0002-0000-0000-000000000002"
}
},
{
"pk": 1,
"model": "exercises.exercise",
@@ -28,7 +14,7 @@
"muscles_secondary": [
3
],
"variations": 1
"variation_group": "a1b2c3d4-0001-0000-0000-000000000001"
}
},
{
@@ -46,7 +32,7 @@
1,
3
],
"variations": 1
"variation_group": "a1b2c3d4-0001-0000-0000-000000000001"
}
},
{
@@ -60,7 +46,7 @@
"muscles": [
1
],
"variations": 2
"variation_group": "a1b2c3d4-0002-0000-0000-000000000002"
}
},
{
@@ -75,7 +61,7 @@
1
],
"muscles_secondary": [],
"variations": 2
"variation_group": "a1b2c3d4-0002-0000-0000-000000000002"
}
},
{
@@ -87,7 +73,7 @@
"created": "2002-08-15T00:00:00+01:00",
"last_update": "2008-08-08T08:08:08+01:00",
"muscles": [],
"variations": null
"variation_group": null
}
},
{
@@ -99,7 +85,7 @@
"created": "2002-08-15T00:00:00+01:00",
"last_update": "2008-08-08T08:08:08+01:00",
"muscles": [],
"variations": null
"variation_group": null
}
},
{
@@ -111,7 +97,7 @@
"created": "2002-08-15T00:00:00+01:00",
"last_update": "2008-08-08T08:08:08+01:00",
"muscles": [],
"variations": null
"variation_group": null
}
},
{
@@ -123,7 +109,7 @@
"created": "2002-08-15T00:00:00+01:00",
"last_update": "2008-08-08T08:08:08+01:00",
"muscles": [],
"variations": null
"variation_group": null
}
},
{

View File

@@ -18,16 +18,11 @@ from argparse import RawTextHelpFormatter
# Django
from django.core.management.base import BaseCommand
# Django
from django.db.models import Count
# wger
from wger.core.models import Language
from wger.exercises.models import (
Exercise,
Variation,
)
from wger.exercises.models import Exercise
from wger.utils.constants import ENGLISH_SHORT_NAME
@@ -125,19 +120,23 @@ class Command(BaseCommand):
def handle_orphan_variations(self, delete: bool):
"""
Find and optionally delete variation groups with fewer than 2 exercises.
Find and optionally clean up variation groups with fewer than 2 exercises.
"""
orphaned = Variation.objects.annotate(
exercise_count=Count('exercise')
).filter(exercise_count__lte=1)
orphaned = (
Exercise.objects.filter(variation_group__isnull=False)
.values('variation_group')
.annotate(count=Count('id'))
.filter(count=1)
)
for variation in orphaned:
for group in orphaned:
self.stdout.write(
self.style.WARNING(
f'Variation {variation.uuid} has {variation.exercise_count} exercise(s)!'
f'Variation group {group["variation_group"]} has only 1 exercise!'
)
)
if delete:
Exercise.objects.filter(variations=variation).update(variations=None)
variation.delete()
self.stdout.write(' -> deleted')
Exercise.objects.filter(variation_group=group['variation_group']).update(
variation_group=None
)
self.stdout.write(' -> cleaned up')

View File

@@ -1,31 +0,0 @@
import uuid as uuid_mod
from django.db import migrations, models
from django.db.migrations.state import StateApps
def generate_variation_uuids(apps: StateApps, schema_editor):
Variation = apps.get_model('exercises', 'Variation')
for variation in Variation.objects.all():
variation.uuid = uuid_mod.uuid4()
variation.save(update_fields=['uuid'])
class Migration(migrations.Migration):
dependencies = [
('exercises', '0035_add_is_ai_generated'),
]
operations = [
migrations.AddField(
model_name='variation',
name='uuid',
field=models.UUIDField(null=True),
),
migrations.RunPython(generate_variation_uuids, migrations.RunPython.noop),
migrations.AlterField(
model_name='variation',
name='uuid',
field=models.UUIDField(default=uuid_mod.uuid4, editable=False, unique=True),
),
]

View File

@@ -0,0 +1,125 @@
"""
Replace the Variation ForeignKey on Exercise with a UUID field.
Exercises with the same variation_group UUID belong to the same group.
The separate Variation model is no longer needed.
Steps:
1. Add UUID field to Variation model (so we have something to copy)
2. Add variation_group UUIDField to Exercise
3. Copy Variation UUIDs to Exercise.variation_group
4. Remove FK + delete model
"""
import uuid as uuid_mod
from django.db import migrations, models
from django.db.backends.base.schema import BaseDatabaseSchemaEditor
from django.db.migrations.state import StateApps
def fix_sqlite_historical_indexes(apps: StateApps, schema_editor: BaseDatabaseSchemaEditor):
"""
Fix index name collision caused by migration 0032_rename_exercise.
When RenameModel renamed HistoricalExercise -> HistoricalTranslation and
HistoricalExerciseBase -> HistoricalExercise, SQLite did not rename the
indexes. The old exercises_historicalexercise_* indexes remain on the
historicaltranslation table, colliding with indexes Django tries to
create for the new HistoricalExercise model.
This only affects SQLite; PostgreSQL renames indexes correctly.
"""
if schema_editor.connection.vendor == 'postgresql':
return
cursor = schema_editor.connection.cursor()
if schema_editor.connection.vendor == 'sqlite':
cursor.execute(
"SELECT name FROM sqlite_master WHERE type='index' "
"AND tbl_name='exercises_historicaltranslation' "
"AND name LIKE 'exercises_historicalexercise_%'"
)
for (index_name,) in cursor.fetchall():
cursor.execute(f'DROP INDEX IF EXISTS "{index_name}"')
elif schema_editor.connection.vendor == 'mysql':
cursor.execute(
"SELECT INDEX_NAME FROM INFORMATION_SCHEMA.STATISTICS "
"WHERE TABLE_NAME = 'exercises_historicaltranslation' "
"AND INDEX_NAME LIKE 'exercises_historicalexercise_%%'"
)
for (index_name,) in cursor.fetchall():
cursor.execute(
f'DROP INDEX `{index_name}` ON `exercises_historicaltranslation`'
)
def generate_variation_uuids(apps: StateApps, schema_editor: BaseDatabaseSchemaEditor):
"""Generate UUIDs for existing Variation objects."""
Variation = apps.get_model('exercises', 'Variation')
for variation in Variation.objects.all():
variation.uuid = uuid_mod.uuid4()
variation.save(update_fields=['uuid'])
def copy_variation_uuids(apps: StateApps, schema_editor: BaseDatabaseSchemaEditor):
"""Copy the UUID from each Variation object to the exercises that reference it."""
Exercise = apps.get_model('exercises', 'Exercise')
for exercise in Exercise.objects.filter(variations__isnull=False).select_related('variations'):
exercise.variation_group = exercise.variations.uuid
exercise.save(update_fields=['variation_group'])
class Migration(migrations.Migration):
dependencies = [
('exercises', '0035_add_is_ai_generated'),
]
operations = [
migrations.RunPython(fix_sqlite_historical_indexes, migrations.RunPython.noop),
# Temporarily add UUID to the variation table
migrations.AddField(
model_name='variation',
name='uuid',
field=models.UUIDField(null=True),
),
migrations.RunPython(generate_variation_uuids, migrations.RunPython.noop),
migrations.AddField(
model_name='exercise',
name='variation_group',
field=models.UUIDField(
blank=True,
db_index=True,
null=True,
verbose_name='Variation group',
),
),
migrations.AddField(
model_name='historicalexercise',
name='variation_group',
field=models.UUIDField(
blank=True,
null=True,
verbose_name='Variation group',
),
),
# Copy data and remove FK relations
migrations.RunPython(copy_variation_uuids, migrations.RunPython.noop),
migrations.RemoveField(
model_name='exercise',
name='variations',
),
migrations.RemoveField(
model_name='historicalexercise',
name='variations',
),
# Cleanup
migrations.DeleteModel(
name='Variation',
),
]

View File

@@ -0,0 +1,211 @@
# Generated by Django 5.2.13 on 2026-04-13 09:38
import django.db.models.deletion
import wger.exercises.models.image
import wger.utils.images
from django.db import migrations, models
"""
This migration has no real changes, it just re-syncs every change from the models
back, like help text changes and so.
"""
class Migration(migrations.Migration):
dependencies = [
('exercises', '0036_replace_variation_with_uuid_field'),
]
operations = [
migrations.AlterField(
model_name='deletionlog',
name='replaced_by',
field=models.UUIDField(
default=None,
editable=False,
help_text='UUID of the object replaced by the deleted one. At the moment only available for exercises',
null=True,
verbose_name='Replaced by',
),
),
migrations.AlterField(
model_name='exercise',
name='created',
field=models.DateTimeField(auto_now_add=True, verbose_name='Creation date'),
),
migrations.AlterField(
model_name='exercise',
name='last_update',
field=models.DateTimeField(auto_now=True, verbose_name='last update'),
),
migrations.AlterField(
model_name='exercise',
name='license_author',
field=models.TextField(
blank=True,
help_text='If you are not the author, enter the name or source here.',
max_length=3500,
null=True,
verbose_name='Author(s)',
),
),
migrations.AlterField(
model_name='exerciseimage',
name='image',
field=models.ImageField(
height_field='height',
help_text='Only JPEG, PNG and WebP formats are supported',
upload_to=wger.exercises.models.image.exercise_image_upload_dir,
validators=[wger.utils.images.validate_image_static_no_animation],
verbose_name='Image',
width_field='width',
),
),
migrations.AlterField(
model_name='exerciseimage',
name='is_main',
field=models.BooleanField(default=False, verbose_name='Is main picture'),
),
migrations.AlterField(
model_name='exerciseimage',
name='license_author',
field=models.TextField(
blank=True,
help_text='If you are not the author, enter the name or source here.',
max_length=3500,
null=True,
verbose_name='Author(s)',
),
),
migrations.AlterField(
model_name='exercisevideo',
name='is_main',
field=models.BooleanField(default=False, verbose_name='Is main video'),
),
migrations.AlterField(
model_name='exercisevideo',
name='license_author',
field=models.TextField(
blank=True,
help_text='If you are not the author, enter the name or source here.',
max_length=3500,
null=True,
verbose_name='Author(s)',
),
),
migrations.AlterField(
model_name='historicalexercise',
name='created',
field=models.DateTimeField(blank=True, editable=False, verbose_name='Creation date'),
),
migrations.AlterField(
model_name='historicalexercise',
name='last_update',
field=models.DateTimeField(blank=True, editable=False, verbose_name='last update'),
),
migrations.AlterField(
model_name='historicalexercise',
name='license_author',
field=models.TextField(
blank=True,
help_text='If you are not the author, enter the name or source here.',
max_length=3500,
null=True,
verbose_name='Author(s)',
),
),
migrations.AlterField(
model_name='historicalexercise',
name='variation_group',
field=models.UUIDField(
blank=True, db_index=True, null=True, verbose_name='Variation group'
),
),
migrations.AlterField(
model_name='historicalexerciseimage',
name='image',
field=models.TextField(
help_text='Only JPEG, PNG and WebP formats are supported',
max_length=100,
validators=[wger.utils.images.validate_image_static_no_animation],
verbose_name='Image',
),
),
migrations.AlterField(
model_name='historicalexerciseimage',
name='is_main',
field=models.BooleanField(default=False, verbose_name='Is main picture'),
),
migrations.AlterField(
model_name='historicalexerciseimage',
name='license_author',
field=models.TextField(
blank=True,
help_text='If you are not the author, enter the name or source here.',
max_length=3500,
null=True,
verbose_name='Author(s)',
),
),
migrations.AlterField(
model_name='historicalexercisevideo',
name='is_main',
field=models.BooleanField(default=False, verbose_name='Is main video'),
),
migrations.AlterField(
model_name='historicalexercisevideo',
name='license_author',
field=models.TextField(
blank=True,
help_text='If you are not the author, enter the name or source here.',
max_length=3500,
null=True,
verbose_name='Author(s)',
),
),
migrations.AlterField(
model_name='historicaltranslation',
name='exercise',
field=models.ForeignKey(
blank=True,
db_constraint=False,
default=None,
null=True,
on_delete=django.db.models.deletion.DO_NOTHING,
related_name='+',
to='exercises.exercise',
),
),
migrations.AlterField(
model_name='historicaltranslation',
name='license_author',
field=models.TextField(
blank=True,
help_text='If you are not the author, enter the name or source here.',
max_length=3500,
null=True,
verbose_name='Author(s)',
),
),
migrations.AlterField(
model_name='translation',
name='exercise',
field=models.ForeignKey(
default=None,
on_delete=django.db.models.deletion.CASCADE,
related_name='translations',
to='exercises.exercise',
),
),
migrations.AlterField(
model_name='translation',
name='license_author',
field=models.TextField(
blank=True,
help_text='If you are not the author, enter the name or source here.',
max_length=3500,
null=True,
verbose_name='Author(s)',
),
),
]

View File

@@ -24,5 +24,4 @@ from .exercise_alias import Alias
from .image import ExerciseImage
from .muscle import Muscle
from .translation import Translation
from .variation import Variation
from .video import ExerciseVideo

View File

@@ -55,7 +55,6 @@ from wger.utils.models import (
from .category import ExerciseCategory
from .equipment import Equipment
from .muscle import Muscle
from .variation import Variation
class Exercise(AbstractLicenseModel, AbstractHistoryMixin, models.Model):
@@ -106,14 +105,13 @@ class Exercise(AbstractLicenseModel, AbstractHistoryMixin, models.Model):
)
"""Equipment needed by this exercise"""
variations = models.ForeignKey(
Variation,
verbose_name='Variations',
on_delete=models.SET_NULL,
variation_group = models.UUIDField(
verbose_name='Variation group',
null=True,
blank=True,
db_index=True,
)
"""Variations of this exercise"""
"""Exercises with the same variation_group UUID belong together"""
created = models.DateTimeField(
'Creation date',
@@ -213,9 +211,9 @@ class Exercise(AbstractLicenseModel, AbstractHistoryMixin, models.Model):
"""
Returns the variations of this exercise base, excluding itself
"""
if not self.variations:
if not self.variation_group:
return []
return self.variations.exercise_set.filter(~Q(id=self.id))
return Exercise.objects.filter(variation_group=self.variation_group).exclude(id=self.id)
def get_translation(self, language: Optional[str] = None):
"""
@@ -280,6 +278,6 @@ class Exercise(AbstractLicenseModel, AbstractHistoryMixin, models.Model):
SlotEntry.objects.filter(exercise=self).update(exercise=replacement)
WorkoutLog.objects.filter(exercise=self).update(exercise=replacement)
reset_exercise_api_cache(self.uuid)
reset_exercise_api_cache(str(self.uuid))
return super().delete(using, keep_parents)

View File

@@ -103,7 +103,8 @@ class Translation(AbstractLicenseModel, AbstractHistoryMixin, models.Model):
ordering = [
'name',
]
indexes = (GinIndex(fields=['name']),)
indexes = (GinIndex(fields=['name'], name='exercises_e_name_ac11f4_gin'),)
# indexes = (GinIndex(fields=['name']),)
constraints = [
models.UniqueConstraint(
fields=['exercise', 'language'],
@@ -181,10 +182,9 @@ class Translation(AbstractLicenseModel, AbstractHistoryMixin, models.Model):
Returns the variations for this exercise in the same language
"""
out = []
if self.exercise.variations:
for variation in self.exercise.variations.exercise_set.all():
for exercise in variation.translations.filter(language=self.language).all():
out.append(exercise)
for variation in self.exercise.base_variations:
for translation in variation.translations.filter(language=self.language).all():
out.append(translation)
return out
#

View File

@@ -1,45 +0,0 @@
# This file is part of wger Workout Manager <https://github.com/wger-project>.
# Copyright (C) 2013 - 2021 wger Team
#
# 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Standard Library
import uuid
# Django
from django.db import models
class Variation(models.Model):
"""
Variation ids for exercises
"""
uuid = models.UUIDField(
default=uuid.uuid4,
editable=False,
unique=True,
)
def __str__(self):
"""
Return a more human-readable representation
"""
return f'Variation {self.id}'
def get_owner_object(self):
"""
Variation has no owner information
"""
return False

View File

@@ -17,7 +17,6 @@
# Django
from django.db.models.signals import (
post_delete,
post_save,
pre_delete,
pre_save,
)
@@ -31,11 +30,9 @@ from easy_thumbnails.signals import saved_file
# wger
from wger.exercises.models import (
DeletionLog,
Exercise,
ExerciseImage,
ExerciseVideo,
Translation,
Variation,
)
@@ -127,43 +124,3 @@ def add_deletion_log_video(sender, instance: ExerciseVideo, **kwargs):
model_type=DeletionLog.MODEL_VIDEO,
uuid=instance.uuid,
).save()
@receiver(pre_save, sender=Exercise)
def store_previous_variation(sender, instance: Exercise, **kwargs):
"""
Store the previous variation ID before saving so we can clean up
orphaned groups afterwards.
"""
if instance.pk:
instance._previous_variation_id = (
Exercise.objects.filter(pk=instance.pk)
.values_list('variations_id', flat=True)
.first()
)
else:
instance._previous_variation_id = None
@receiver(post_save, sender=Exercise)
def cleanup_orphaned_variation(sender, instance: Exercise, **kwargs):
"""
Clean up the previous variation group if it now has fewer than 2 exercises.
A variation with only 1 exercise makes no sense, so we unlink the
remaining exercise and delete the variation.
Note: it's necessary to handle this case like this because the naive option
of just removing all variations with only one (or none) exercises won't work,
as it would prevent any variations from being created since there will always
be a moment where there is only one exercise in the variation.
"""
previous_id = getattr(instance, '_previous_variation_id', None)
if previous_id is None or previous_id == instance.variations_id:
return
members = Exercise.objects.filter(variations_id=previous_id)
count = members.count()
if count <= 1:
members.update(variations=None)
Variation.objects.filter(pk=previous_id).delete()

View File

@@ -52,7 +52,6 @@ from wger.exercises.models import (
ExerciseVideo,
Muscle,
Translation,
Variation,
)
from wger.manager.models import (
SlotEntry,
@@ -85,20 +84,12 @@ def sync_exercises(
muscles = [Muscle.objects.get(pk=i['id']) for i in data['muscles']]
muscles_sec = [Muscle.objects.get(pk=i['id']) for i in data['muscles_secondary']]
# Sync variation group by UUID
remote_variation_uuid = data.get('variations')
local_variation = None
if remote_variation_uuid is not None:
local_variation, _ = Variation.objects.get_or_create(
uuid=remote_variation_uuid,
)
exercise, exercise_created = Exercise.objects.update_or_create(
uuid=uuid,
defaults={
'category_id': category_id,
'created': created,
'variations': local_variation,
'variation_group': data.get('variation_group'),
},
)
print_fn(f'{"created" if exercise_created else "updated"} exercise {uuid}')

View File

@@ -27,7 +27,6 @@ from wger.exercises.models import (
Exercise,
ExerciseComment,
Translation,
Variation,
)
@@ -43,7 +42,7 @@ class SearchSubmissionApiTestCase(BaseTestCase, ApiBaseTestCase):
'muscles_secondary': [1],
'equipment': [3],
'license_author': 'test man',
'variations': 1,
'variation_group': 'a1b2c3d4-0001-0000-0000-000000000001',
'translations': [
{
'name': '1-Arm Half-Kneeling Lat Pulldown',
@@ -71,14 +70,13 @@ class SearchSubmissionApiTestCase(BaseTestCase, ApiBaseTestCase):
@staticmethod
def get_counts():
Counts = namedtuple('Counts', ['exercise', 'translation', 'alias', 'comment', 'variations'])
Counts = namedtuple('Counts', ['exercise', 'translation', 'alias', 'comment'])
return Counts(
Exercise.objects.count(),
Translation.objects.count(),
Alias.objects.count(),
ExerciseComment.objects.count(),
Variation.objects.count(),
)
def test_successful_submission_full(self):
@@ -98,7 +96,7 @@ class SearchSubmissionApiTestCase(BaseTestCase, ApiBaseTestCase):
self.assertEqual(list(exercise.muscles_secondary.values_list('id', flat=True)), [1])
self.assertEqual(list(exercise.equipment.values_list('id', flat=True)), [3])
self.assertEqual(exercise.license_author, 'test man')
self.assertEqual(exercise.variations_id, 1)
self.assertEqual(str(exercise.variation_group), 'a1b2c3d4-0001-0000-0000-000000000001')
self.assertEqual(before.exercise + 1, after.exercise)
self.assertEqual(before.translation + 2, after.translation)
@@ -114,7 +112,7 @@ class SearchSubmissionApiTestCase(BaseTestCase, ApiBaseTestCase):
payload['muscles_secondary'] = []
payload['muscles'] = []
payload['equipment'] = []
payload['variations'] = None
payload['variation_group'] = None
before = self.get_counts()
response_data = self.client.post(self.url, data=payload).json()
@@ -127,7 +125,7 @@ class SearchSubmissionApiTestCase(BaseTestCase, ApiBaseTestCase):
self.assertEqual(list(exercise.muscles_secondary.values_list('id', flat=True)), [])
self.assertEqual(list(exercise.equipment.values_list('id', flat=True)), [])
self.assertEqual(exercise.license_author, 'test man')
self.assertEqual(exercise.variations_id, None)
self.assertIsNone(exercise.variation_group)
self.assertEqual(before.exercise + 1, after.exercise)
self.assertEqual(before.translation + 2, after.translation)
@@ -185,17 +183,15 @@ class SearchSubmissionApiTestCase(BaseTestCase, ApiBaseTestCase):
payload = self.get_payload()
payload['variations_connect_to'] = 5
del payload['variations']
del payload['variation_group']
connected_exercise = Exercise.objects.get(pk=5)
self.assertIsNone(connected_exercise.variations_id)
self.assertIsNone(connected_exercise.variation_group)
counts_before = self.get_counts()
response = self.client.post(self.url, data=payload)
exercise = Exercise.objects.get(pk=response.json().get('id'))
connected_exercise.refresh_from_db()
counts_after = self.get_counts()
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(counts_before.variations + 1, counts_after.variations)
self.assertEqual(exercise.variations_id, connected_exercise.variations_id)
self.assertIsNotNone(exercise.variation_group)
self.assertEqual(exercise.variation_group, connected_exercise.variation_group)

View File

@@ -105,7 +105,7 @@ class ExerciseCustomApiTestCase(ExerciseCrudApiTestCase):
'muscles': [1, 3],
'muscles_secondary': [2],
'equipment': [3],
'variations': 1,
'variation_group': 'a1b2c3d4-0001-0000-0000-000000000001',
}
def get_resource_name(self):

View File

@@ -1,110 +0,0 @@
# 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
from wger.core.tests.base_testcase import WgerTestCase
from wger.exercises.models import (
Exercise,
Variation,
)
class CleanupOrphanedVariationsTestCase(WgerTestCase):
"""
Test that the post_save signal on Exercise cleans up variation groups
that have fewer than 2 exercises.
"""
def test_removing_exercise_from_group_of_two_cleans_up(self):
"""
When a group has 2 exercises and one is removed, the remaining
exercise should be unlinked and the variation deleted.
"""
# Variation 1 has 2 exercises in the test fixtures
variation = Variation.objects.get(pk=1)
members = Exercise.objects.filter(variations=variation)
self.assertEqual(members.count(), 2)
other_pk = members.exclude(pk=members.first().pk).first().pk
# Remove one exercise from the group
exercise = members.first()
exercise.variations = None
exercise.save()
# The variation should be deleted and the other exercise unlinked
self.assertFalse(Variation.objects.filter(pk=1).exists())
other = Exercise.objects.get(pk=other_pk)
self.assertIsNone(other.variations)
def test_removing_exercise_from_larger_group_keeps_group(self):
"""
When a group has 3+ exercises and one is removed, the group
should remain intact.
"""
# Add a third exercise to variation 1
variation = Variation.objects.get(pk=1)
ex = Exercise.objects.filter(variations__isnull=True).first()
ex.variations = variation
ex.save()
self.assertEqual(
Exercise.objects.filter(variations=variation).count(), 3
)
# Remove one exercise
first = Exercise.objects.filter(variations=variation).first()
first.variations = None
first.save()
# The group should still exist with 2 members
self.assertTrue(Variation.objects.filter(pk=variation.pk).exists())
self.assertEqual(
Exercise.objects.filter(variations=variation).count(), 2
)
def test_moving_exercise_to_different_group_cleans_up_old(self):
"""
When an exercise is moved from a 2-exercise group to another group,
the old group should be cleaned up.
"""
old_variation = Variation.objects.get(pk=1)
new_variation = Variation.objects.get(pk=2)
self.assertEqual(
Exercise.objects.filter(variations=old_variation).count(), 2
)
# Move one exercise to the other group
exercise = Exercise.objects.filter(variations=old_variation).first()
exercise.variations = new_variation
exercise.save()
# Old variation should be cleaned up
self.assertFalse(Variation.objects.filter(pk=old_variation.pk).exists())
def test_saving_without_change_does_nothing(self):
"""
Saving an exercise without changing its variation should not
affect the group.
"""
variation = Variation.objects.get(pk=2)
count_before = Exercise.objects.filter(variations=variation).count()
# Save without changing variation
exercise = Exercise.objects.filter(variations=variation).first()
exercise.save()
# Nothing should change
self.assertTrue(Variation.objects.filter(pk=variation.pk).exists())
self.assertEqual(
Exercise.objects.filter(variations=variation).count(),
count_before,
)

View File

@@ -28,7 +28,6 @@ from wger.core.tests.base_testcase import WgerTestCase
from wger.exercises.models import (
Exercise,
Translation,
Variation,
)
@@ -121,38 +120,37 @@ class TestHealthCheckManagementCommands(WgerTestCase):
self.assertIn('-> deleted', self.out.getvalue())
self.assertRaises(Exercise.DoesNotExist, Exercise.objects.get, pk=1)
def test_find_orphan_variation_empty(self):
"""Variation with 0 exercises is reported"""
orphan = Variation.objects.create()
call_command('exercises-health-check', stdout=self.out)
self.assertIn(f'Variation {orphan.uuid} has 0 exercise(s)!', self.out.getvalue())
self.assertNotIn('-> deleted', self.out.getvalue())
def test_find_orphan_variation_single(self):
"""Variation with 1 exercise is reported"""
"""Variation group with 1 exercise is reported"""
# Standard Library
import uuid
variation = Variation.objects.get(pk=1)
# Remove one exercise so only 1 remains
exercise = Exercise.objects.filter(variations=variation).first()
Exercise.objects.filter(pk=exercise.pk).update(variations=None)
# Set one exercise to a unique variation group alone
exercise = Exercise.objects.get(pk=5)
group_uuid = uuid.uuid4()
exercise.variation_group = group_uuid
exercise.save()
call_command('exercises-health-check', stdout=self.out)
self.assertIn(f'Variation {variation.uuid} has 1 exercise(s)!', self.out.getvalue())
self.assertIn(f'Variation group {group_uuid} has only 1 exercise!', self.out.getvalue())
def test_fix_orphan_variations(self):
"""--delete-orphan-variations removes orphaned variations"""
"""--delete-orphan-variations cleans up single-exercise groups"""
# Standard Library
import uuid
orphan = Variation.objects.create()
orphan_pk = orphan.pk
exercise = Exercise.objects.get(pk=5)
group_uuid = uuid.uuid4()
exercise.variation_group = group_uuid
exercise.save()
call_command('exercises-health-check', '--delete-orphan-variations', stdout=self.out)
self.assertIn('-> deleted', self.out.getvalue())
self.assertFalse(Variation.objects.filter(pk=orphan_pk).exists())
self.assertIn('-> cleaned up', self.out.getvalue())
exercise.refresh_from_db()
self.assertIsNone(exercise.variation_group)
def test_healthy_variations_not_affected(self):
"""Variations with 2+ exercises are not reported"""
"""Variation groups with 2+ exercises are not reported"""
call_command('exercises-health-check', stdout=self.out)
self.assertNotIn('Variation', self.out.getvalue())

View File

@@ -436,7 +436,7 @@ class MockExerciseResponse:
]
}
],
"variations": "4e1bb2fc-3b0e-4a1a-bd3e-3728a0e6d8a7",
"variation_group": "4e1bb2fc-3b0e-4a1a-bd3e-3728a0e6d8a7",
"videos": [],
"author_history": [
"Mrs Winterbottom"
@@ -552,7 +552,7 @@ class MockExerciseResponse:
]
}
],
"variations": "4e1bb2fc-3b0e-4a1a-bd3e-3728a0e6d8a7",
"variation_group": "4e1bb2fc-3b0e-4a1a-bd3e-3728a0e6d8a7",
"videos": [],
"author_history": [
"Mr X"
@@ -796,11 +796,11 @@ class TestSyncMethods(WgerTestCase):
self.assertEqual(str(translation_fr.uuid), '581338a1-8e52-405b-99eb-f0724c528bc8')
# Both exercises should be in the same variation group
self.assertIsNotNone(new_exercise.variations)
self.assertIsNotNone(exercise.variations)
self.assertEqual(new_exercise.variations, exercise.variations)
self.assertIsNotNone(new_exercise.variation_group)
self.assertIsNotNone(exercise.variation_group)
self.assertEqual(new_exercise.variation_group, exercise.variation_group)
self.assertEqual(
str(new_exercise.variations.uuid),
str(new_exercise.variation_group),
'4e1bb2fc-3b0e-4a1a-bd3e-3728a0e6d8a7',
)

View File

@@ -203,11 +203,6 @@ router.register(
exercises_api_views.MuscleViewSet,
basename='muscle',
)
router.register(
r'variation',
exercises_api_views.ExerciseVariationViewSet,
basename='variation',
)
# Nutrition app
router.register(r'ingredient', nutrition_api_views.IngredientViewSet, basename='api-ingredient')