Self hosted FLOSS fitness/workout, nutrition and weight tracker
Properly prefetch all necessary queries
Roland Geider946dd7065855
diff --git a/wger/core/models/weight_unit.py b/wger/core/models/weight_unit.pyindex 0c1f22351..3f9f0c6ab 100644--- a/wger/core/models/weight_unit.py+++ b/wger/core/models/weight_unit.py@@ -18,6 +18,12 @@from django.db import modelsfrom django.utils.translation import gettext_lazy as _+# wger+from wger.manager.consts import (+ WEIGHT_UNIT_KG,+ WEIGHT_UNIT_LB,+)+class WeightUnit(models.Model):"""@@ -52,9 +58,4 @@ class WeightUnit(models.Model):@propertydef is_weight(self):- """- Checks that the unit is a weight proper-- This is done basically to not litter the code with magic IDs- """- return self.id in (1, 2)+ return self.id in (WEIGHT_UNIT_KG, WEIGHT_UNIT_LB)diff --git a/wger/manager/api/views.py b/wger/manager/api/views.pyindex 5422a1669..666cbf3dc 100644--- a/wger/manager/api/views.py+++ b/wger/manager/api/views.py@@ -120,12 +120,16 @@ class RoutineViewSet(viewsets.ModelViewSet):# profiler = cProfile.Profile()# profiler.enable()- cache_key = CacheKeyMapper.get_routine_api_date_sequence_key(pk)+ cache_key = CacheKeyMapper.routine_api_date_sequence_display_key(pk)cached_data = cache.get(cache_key)if cached_data is not None:return Response(cached_data)- out = WorkoutDayDataDisplayModeSerializer(self.get_object().date_sequence, many=True).data+ out = WorkoutDayDataDisplayModeSerializer(+ self.get_object().date_sequence,+ # generate_sequence(self.get_object()),+ many=True,+ ).datacache.set(cache_key, out, settings.WGER_SETTINGS['ROUTINE_CACHE_TTL'])# profiler.disable()@@ -138,23 +142,15 @@ class RoutineViewSet(viewsets.ModelViewSet):"""Return the day sequence of the routine"""- return Response(- WorkoutDayDataGymModeSerializer(self.get_object().date_sequence, many=True).data- )+ cache_key = CacheKeyMapper.routine_api_date_sequence_gym_key(pk)+ cached_data = cache.get(cache_key)+ if cached_data is not None:+ return Response(cached_data)- @action(detail=True, url_path='current-day-display')- def current_day_display_mode(self, request, pk):- """- Return current day of the routine- """- return Response(WorkoutDayDataDisplayModeSerializer(self.get_object().data_for_day()).data)+ out = WorkoutDayDataGymModeSerializer(self.get_object().date_sequence, many=True).data+ cache.set(cache_key, out, settings.WGER_SETTINGS['ROUTINE_CACHE_TTL'])- @action(detail=True, url_path='current-day-gym')- def current_day_gym_mode(self, request, pk):- """- Return current day of the routine- """- return Response(WorkoutDayDataGymModeSerializer(self.get_object().data_for_day()).data)+ return Response(out)@action(detail=True)def structure(self, request, pk):diff --git a/wger/manager/consts.py b/wger/manager/consts.pyindex 00e66538e..cbd1aaba1 100644--- a/wger/manager/consts.py+++ b/wger/manager/consts.py@@ -27,6 +27,7 @@ RIR_OPTIONS = [('4', 4),]-ID_UNIT_REPETITIONS = 1-ID_UNIT_KG = 1-ID_UNIT_LB = 2+REP_UNIT_REPETITIONS = 1+REP_UNIT_TILL_FAILURE = 2+WEIGHT_UNIT_KG = 1+WEIGHT_UNIT_LB = 2diff --git a/wger/manager/dataclasses.py b/wger/manager/dataclasses.pyindex ccc9c7232..31b3be81e 100644--- a/wger/manager/dataclasses.py+++ b/wger/manager/dataclasses.py@@ -40,6 +40,10 @@ from wger.core.models import (RepetitionUnit,WeightUnit,)+from wger.manager.consts import (+ REP_UNIT_REPETITIONS,+ REP_UNIT_TILL_FAILURE,+)@dataclass@@ -48,12 +52,14 @@ class SetConfigData:weight: Decimal | int | None = Nonemax_weight: Decimal | int | None = None- weight_unit: int | None = 1+ weight_unit: int | None = None+ weight_unit_name: str | None = Noneweight_rounding: Decimal | int | None = Nonerepetitions: Decimal | int | None = Nonemax_repetitions: Decimal | int | None = None- repetitions_unit: int | None = 1+ repetitions_unit: int | None = None+ repetitions_unit_name: str | None = Nonerepetitions_rounding: Decimal | int | None = Nonerir: Decimal | int | None = None@@ -111,13 +117,19 @@ class SetConfigData:reps = f'{reps}-{max_reps}'unit = ''- if self.repetitions_unit in (1, 2) and not self.weight:+ if (+ self.repetitions_unit in (REP_UNIT_REPETITIONS, REP_UNIT_TILL_FAILURE)+ and not self.weight+ ):unit = _('Reps')- elif self.repetitions_unit == 2:+ elif self.repetitions_unit == REP_UNIT_TILL_FAILURE:unit = '∞'reps = ''- elif self.repetitions_unit not in (1, 2):- unit = _(RepetitionUnit.objects.get(pk=self.repetitions_unit).name)+ elif self.repetitions_unit is not None and self.repetitions_unit not in (+ REP_UNIT_REPETITIONS,+ REP_UNIT_TILL_FAILURE,+ ):+ unit = _(self.repetitions_unit_name)out.append(f'{reps} {unit}'.strip())@@ -137,7 +149,7 @@ class SetConfigData:unit = ''if self.weight_unit:- unit = _(WeightUnit.objects.get(pk=self.weight_unit).name)+ unit = _(self.weight_unit_name)out.append(f'{weight} {unit}'.strip())diff --git a/wger/manager/fixtures/test-routine-data.json b/wger/manager/fixtures/test-routine-data.jsonindex d258d14d5..5501929d0 100644--- a/wger/manager/fixtures/test-routine-data.json+++ b/wger/manager/fixtures/test-routine-data.json@@ -141,8 +141,7 @@"order": 1,"comment": "","type": "normal",- "class_name": null,- "has_progression": false+ "class_name": null}},{@@ -158,8 +157,7 @@"order": 1,"comment": "","type": "normal",- "class_name": null,- "has_progression": false+ "class_name": null}},{@@ -175,8 +173,7 @@"order": 1,"comment": "","type": "normal",- "class_name": null,- "has_progression": false+ "class_name": null}},{@@ -192,8 +189,7 @@"order": 1,"comment": "","type": "normal",- "class_name": null,- "has_progression": false+ "class_name": null}},{diff --git a/wger/manager/helpers.py b/wger/manager/helpers.pyindex 550920d22..93c76b1cf 100644--- a/wger/manager/helpers.py+++ b/wger/manager/helpers.py@@ -186,7 +186,8 @@ def reset_routine_cache(instance: Routine):"""Resets all caches related to a routine"""cache.delete(CacheKeyMapper.get_routine_date_sequence_key(instance.id))- cache.delete(CacheKeyMapper.get_routine_api_date_sequence_key(instance.id))+ cache.delete(CacheKeyMapper.routine_api_date_sequence_display_key(instance.id))+ cache.delete(CacheKeyMapper.routine_api_date_sequence_gym_key(instance.id))cache.delete(CacheKeyMapper.get_routine_api_structure_key(instance.id))cache.delete(CacheKeyMapper.get_routine_api_stats(instance.id))diff --git a/wger/manager/managers.py b/wger/manager/managers.pyindex 7a43daef6..7d25372e7 100644--- a/wger/manager/managers.py+++ b/wger/manager/managers.py@@ -19,24 +19,24 @@ from django.db import models# wgerfrom wger.manager.consts import (- ID_UNIT_KG,- ID_UNIT_LB,- ID_UNIT_REPETITIONS,+ REP_UNIT_REPETITIONS,+ WEIGHT_UNIT_KG,+ WEIGHT_UNIT_LB,)class WorkoutLogQuerySet(models.QuerySet):def kg(self):"""Return all entries with kg as weight"""- return self.filter(weight_unit_id=ID_UNIT_KG)+ return self.filter(weight_unit_id=WEIGHT_UNIT_KG)def lb(self):"""Return all entries with lb as weight"""- return self.filter(weight_unit_id=ID_UNIT_LB)+ return self.filter(weight_unit_id=WEIGHT_UNIT_LB)def reps(self):"""Return all entries with reps as unit"""- return self.filter(repetitions_unit_id=ID_UNIT_REPETITIONS)+ return self.filter(repetitions_unit_id=REP_UNIT_REPETITIONS)class WorkoutLogManager(models.Manager):diff --git a/wger/manager/migrations/0018_flexible_routines.py b/wger/manager/migrations/0018_flexible_routines.pyindex c9037a000..056bd533d 100644--- a/wger/manager/migrations/0018_flexible_routines.py+++ b/wger/manager/migrations/0018_flexible_routines.py@@ -462,6 +462,13 @@ class Migration(migrations.Migration):to='manager.routine',),),+ migrations.AddIndex(+ model_name='workoutsession',+ index=models.Index(+ fields=['routine', 'date'],+ name='manager_wor_routine_224494_idx',+ ),+ ),migrations.AlterUniqueTogether(name='workoutsession',unique_together={('date', 'user', 'routine')},diff --git a/wger/manager/migrations/0022_slotentry_has_progression.py b/wger/manager/migrations/0022_slotentry_has_progression.pydeleted file mode 100644index e03456baf..000000000--- a/wger/manager/migrations/0022_slotentry_has_progression.py+++ /dev/null@@ -1,17 +0,0 @@-# Generated by Django 4.2.16 on 2025-02-12 19:23--from django.db import migrations, models---class Migration(migrations.Migration):- dependencies = [- ('manager', '0021_flexible_routines_cleanup'),- ]-- operations = [- migrations.AddField(- model_name='slotentry',- name='has_progression',- field=models.BooleanField(default=False, editable=False),- ),- ]diff --git a/wger/manager/models/day.py b/wger/manager/models/day.pyindex 3caa8c675..3e7437390 100644--- a/wger/manager/models/day.py+++ b/wger/manager/models/day.py@@ -133,7 +133,7 @@ class Day(models.Model):"""if (not self.need_logs_to_advance- or self.workoutsession_set.filter(date=date).exists()+ # or self.workoutsession_set.filter(date=date).exists()or date > datetime.date.today()):return True@@ -144,9 +144,9 @@ class Day(models.Model):"""Return the sets for this day"""- return [- SlotData(comment=s.comment, sets=s.set_data_gym(iteration)) for s in self.slots.all()- ]+ slots = getattr(self, 'prefetched_slots', self.slots.all())++ return [SlotData(comment=s.comment, sets=s.set_data_gym(iteration)) for s in slots]def get_slots_display_mode(self, iteration: int) -> List[SlotData]:"""@@ -170,11 +170,8 @@ class Day(models.Model):out = []last_exercise_id = Nonecurrent_slot = None- # slots = self.slots.prefetch_related(- # Prefetch('entries', to_attr='prefetched_entries')- # ).all()- slots = self.slots.all()+ slots = getattr(self, 'prefetched_slots', self.slots.all())for slot in slots:# for slot in self.slots.all():diff --git a/wger/manager/models/log.py b/wger/manager/models/log.pyindex 0721a103c..13bb8f579 100644--- a/wger/manager/models/log.py+++ b/wger/manager/models/log.py@@ -20,7 +20,6 @@ import datetime# Djangofrom django.contrib.auth.models import Userfrom django.core.exceptions import ValidationError-from django.core.validators import MinValueValidatorfrom django.db import modelsfrom django.utils.translation import gettext_lazy as _@@ -31,9 +30,9 @@ from wger.core.models import ()from wger.exercises.models import Exercisefrom wger.manager.consts import (- ID_UNIT_KG,- ID_UNIT_REPETITIONS,+ REP_UNIT_REPETITIONS,RIR_OPTIONS,+ WEIGHT_UNIT_KG,)from wger.manager.managers import WorkoutLogManagerfrom wger.manager.models.session import WorkoutSession@@ -111,7 +110,7 @@ class WorkoutLog(models.Model):repetitions_unit = models.ForeignKey(RepetitionUnit,verbose_name=_('Unit'),- default=ID_UNIT_REPETITIONS,+ default=REP_UNIT_REPETITIONS,on_delete=models.CASCADE,)"""@@ -144,7 +143,7 @@ class WorkoutLog(models.Model):weight_unit = models.ForeignKey(WeightUnit,verbose_name=_('Unit'),- default=ID_UNIT_KG,+ default=WEIGHT_UNIT_KG,on_delete=models.CASCADE,)"""diff --git a/wger/manager/models/routine.py b/wger/manager/models/routine.pyindex 2ad1fcea9..0c70cc65d 100644--- a/wger/manager/models/routine.py+++ b/wger/manager/models/routine.py@@ -17,7 +17,10 @@# Standard Libraryimport datetimeimport logging-from collections import Counter+from collections import (+ Counter,+ defaultdict,+)from decimal import Decimalfrom typing import List@@ -27,6 +30,7 @@ from django.contrib.auth.models import Userfrom django.core.cache import cachefrom django.core.exceptions import ValidationErrorfrom django.db import models+from django.db.models import Prefetchfrom django.urls import reversefrom django.utils.translation import gettext_lazy as _@@ -182,67 +186,126 @@ class Routine(models.Model):if cached_data is not None:return cached_data- labels = self.label_dict+ # wger+ from wger.manager.models import (+ Slot,+ SlotEntry,+ )++ # Prefetch all config relationships to avoid N+1 queries+ days = (+ Day.objects.filter(routine=self)+ .prefetch_related(+ Prefetch(+ 'slots',+ queryset=Slot.objects.prefetch_related(+ Prefetch(+ 'entries',+ queryset=SlotEntry.objects.prefetch_related(+ 'repetition_unit',+ 'weight_unit',+ 'weightconfig_set',+ 'maxweightconfig_set',+ 'repetitionsconfig_set',+ 'maxrepetitionsconfig_set',+ 'rirconfig_set',+ 'maxrirconfig_set',+ 'restconfig_set',+ 'maxrestconfig_set',+ 'setsconfig_set',+ 'maxsetsconfig_set',+ # Prefetch logs with sessions+ Prefetch(+ 'workoutlog_set',+ queryset=WorkoutLog.objects.select_related('session'),+ # to_attr='prefetched_logs'+ ),+ ),+ to_attr='prefetched_entries',+ )+ ),+ to_attr='prefetched_slots',+ ),+ 'workoutsession_set',+ )+ .order_by('order')+ )++ # Precompute session dates from prefetched logs+ day_session_map = defaultdict(set)+ for day in days:+ for session in day.workoutsession_set.all():+ day_session_map[day.id].add(session.date)++ # Main sequence generation logicdelta = datetime.timedelta(days=1)current_date = self.start- days = list(self.days.all())- nr_days = len(days)+ days_list = list(days)+ days_count = len(days_list)counter = Counter()- skip_til_date = None+ skip_until = None+ sequence = []- out = []+ if not days_list:+ return []- logs = {}- for day in self.days.all():- # logger.debug(f'fetching log data for day {day.pk}')- logs[day.id] = list(WorkoutLog.objects.filter(slot_entry__slot__day=day))+ current_day = days_list[0]+ index = 0- if not days:- return out+ # Precompute label dates+ label_dates = defaultdict(str)+ for label in self.labels.all():+ for i in range(label.start_offset, label.end_offset + 1):+ label_dates[self.start + datetime.timedelta(days=i)] = label.label- index = 0- current_day: Day = days[0]while current_date <= self.end:- # Fill all days till the end of the week with empty workout days- if skip_til_date:- out.append(- WorkoutDayData(- iteration=counter[current_day],- date=current_date,- day=None,- label=labels.get(current_date),+ if skip_until:+ if current_date >= skip_until:+ skip_until = None+ else:+ sequence.append(+ WorkoutDayData(+ iteration=counter[current_day],+ date=current_date,+ day=None,+ label=label_dates.get(current_date),+ ))- )- current_date += delta- if current_date == skip_til_date:- skip_til_date = None- continue+ current_date += delta+ continuecounter[current_day] += 1- index = (index + 1) % nr_days-- # If we reach the end of the available days, check whether we want to fill up the- # week with empty days, unless the routine already consists of 7 training days- if self.fit_in_week and nr_days % 7 != 0 and index == 0:- days_til_monday = 7 - current_date.weekday()- skip_til_date = current_date + datetime.timedelta(days=days_til_monday)+ index = (index + 1) % days_count++ # Handle week filling logic+ if self.fit_in_week and days_count % 7 != 0 and index == 0:+ days_to_monday = 7 - current_date.weekday()+ skip_until = current_date + datetime.timedelta(days=days_to_monday)++ # Check if day can proceed using prefetched session dates+ has_session = current_date in day_session_map[current_day.id]+ can_proceed = (+ not current_day.need_logs_to_advance+ or has_session+ or current_date > datetime.date.today()+ )- out.append(+ sequence.append(WorkoutDayData(iteration=counter[current_day],date=current_date,day=current_day,- label=labels.get(current_date),+ label=label_dates.get(current_date),))- if current_day.can_proceed(current_date):- current_day = days[index]+ if can_proceed:+ current_day = days_list[index]current_date += delta- cache.set(cache_key, out, settings.WGER_SETTINGS['ROUTINE_CACHE_TTL'])- return out+ cache.set(cache_key, sequence, settings.WGER_SETTINGS['ROUTINE_CACHE_TTL'])+ return sequencedef data_for_day(self, date=None) -> WorkoutDayData | None:"""diff --git a/wger/manager/models/session.py b/wger/manager/models/session.pyindex 39d230e70..76011c2c5 100644--- a/wger/manager/models/session.py+++ b/wger/manager/models/session.py@@ -133,6 +133,7 @@ class WorkoutSession(models.Model):'date',]unique_together = ('date', 'user', 'routine')+ indexes = [models.Index(fields=['routine', 'date'])]def clean(self):"""diff --git a/wger/manager/models/slot.py b/wger/manager/models/slot.pyindex 00ffd8d26..32009dc2d 100644--- a/wger/manager/models/slot.py+++ b/wger/manager/models/slot.py@@ -70,14 +70,14 @@ class Slot(models.Model):"""Checks whether this slot is a superset or not"""- return self.entries.count() > 1+ entries = getattr(self, 'prefetched_entries', self.entries.all())+ return len(entries) > 1def set_data(self, iteration: int) -> List[SetExerciseData]:"""Calculates the set data for a specific iteration"""+ entries = getattr(self, 'prefetched_entries', self.entries.all())- result = [- SetExerciseData(data=s.get_config_data(iteration), config=s) for s in self.entries.all()- ]+ result = [SetExerciseData(data=e.get_config_data(iteration), config=e) for e in entries]return resultdiff --git a/wger/manager/models/slot_entry.py b/wger/manager/models/slot_entry.pyindex a66dbc737..5c567151c 100644--- a/wger/manager/models/slot_entry.py+++ b/wger/manager/models/slot_entry.py@@ -29,7 +29,6 @@ from typing import (from django.conf import settingsfrom django.core.cache import cachefrom django.db import models-from django.db.models import QuerySetfrom django.utils.translation import gettext_lazy as _# wger@@ -38,11 +37,14 @@ from wger.core.models import (WeightUnit,)from wger.exercises.models import Exercise+from wger.manager.consts import (+ REP_UNIT_REPETITIONS,+ WEIGHT_UNIT_KG,+)from wger.manager.dataclasses import (SetConfigData,round_value,)-from wger.manager.models import WorkoutLogfrom wger.manager.models.abstract_config import (AbstractChangeConfig,OperationChoices,@@ -96,7 +98,7 @@ class SlotEntry(models.Model):repetition_unit = models.ForeignKey(RepetitionUnit,- default=1,+ default=REP_UNIT_REPETITIONS,on_delete=models.CASCADE,)"""@@ -116,7 +118,7 @@ class SlotEntry(models.Model):weight_unit = models.ForeignKey(WeightUnit,verbose_name=_('Unit'),- default=1,+ default=WEIGHT_UNIT_KG,on_delete=models.CASCADE,)"""@@ -167,14 +169,6 @@ class SlotEntry(models.Model):)"""JSON configuration field for custom behaviour"""- has_progression = models.BooleanField(- default=False,- editable=False,- )- """- Flag indicating if this entry should be used for progression.- """-# Metaclass to set some other propertiesclass Meta:ordering = [@@ -182,7 +176,26 @@ class SlotEntry(models.Model):'id',]- config_entries = {}+ @property+ def has_progression(self) -> bool:+ """+ Returns true if any config set has more than one entry (is a progression)+ """+ return any(+ len(getattr(self, f'{field}config_set').all()) > 1+ for field in [+ 'weight',+ 'maxweight',+ 'repetitions',+ 'maxrepetitions',+ 'rir',+ 'maxrir',+ 'rest',+ 'maxrest',+ 'sets',+ 'maxsets',+ ]+ )def save(self, *args, **kwargs):"""@@ -208,43 +221,48 @@ class SlotEntry(models.Model):def load_all_configs(self, iteration: int) -> Dict[str, Dict[str, List[AbstractChangeConfig] | AbstractChangeConfig]]:- key = CacheKeyMapper.slot_entry_configs_objects_key(self.pk, iteration)- configs = cache.get(key)- if configs is None:- data = {- 'weight': list(self.weightconfig_set.filter(iteration__lte=iteration)),- 'maxweight': list(self.maxweightconfig_set.filter(iteration__lte=iteration)),- 'repetitions': list(self.repetitionsconfig_set.filter(iteration__lte=iteration)),- 'maxrepetitions': list(- self.maxrepetitionsconfig_set.filter(iteration__lte=iteration)- ),- 'rir': list(self.rirconfig_set.filter(iteration__lte=iteration)),- 'maxrir': list(self.maxrirconfig_set.filter(iteration__lte=iteration)),- 'rest': list(self.restconfig_set.filter(iteration__lte=iteration)),- 'maxrest': list(self.maxrestconfig_set.filter(iteration__lte=iteration)),- 'sets': list(self.setsconfig_set.filter(iteration__lte=iteration)),- 'maxsets': list(self.maxsetsconfig_set.filter(iteration__lte=iteration)),- }-- last_entries = {key: data[key][-1] if data[key] else None for key in data}-- configs = {- 'all': data,- 'last': last_entries,- }-- cache.set(- key,- configs,- settings.WGER_SETTINGS['ROUTINE_CACHE_TTL'],- )+ data = {+ 'weight': [c for c in self.weightconfig_set.all() if c.iteration <= iteration],+ 'maxweight': [c for c in self.maxweightconfig_set.all() if c.iteration <= iteration],+ 'repetitions': [+ c for c in self.repetitionsconfig_set.all() if c.iteration <= iteration+ ],+ 'maxrepetitions': [+ c for c in self.maxrepetitionsconfig_set.all() if c.iteration <= iteration+ ],+ 'rir': [c for c in self.rirconfig_set.all() if c.iteration <= iteration],+ 'maxrir': [c for c in self.maxrirconfig_set.all() if c.iteration <= iteration],+ 'rest': [c for c in self.restconfig_set.all() if c.iteration <= iteration],+ 'maxrest': [c for c in self.maxrestconfig_set.all() if c.iteration <= iteration],+ 'sets': [c for c in self.setsconfig_set.all() if c.iteration <= iteration],+ 'maxsets': [c for c in self.maxsetsconfig_set.all() if c.iteration <= iteration],+ }+ last_entries = {key: data[key][-1] if data[key] else None for key in data}++ configs = {+ 'all': data,+ 'last': last_entries,+ }return configsdef get_configuration_entries(self, config_type: ConfigType, iteration) -> List[AbstractChangeConfig]:- return self.load_all_configs(iteration)['all'][config_type.name.lower()]+ configs = {+ ConfigType.WEIGHT: self.weightconfig_set.all(),+ ConfigType.MAXWEIGHT: self.maxweightconfig_set.all(),+ ConfigType.REPETITIONS: self.repetitionsconfig_set.all(),+ ConfigType.MAXREPETITIONS: self.maxrepetitionsconfig_set.all(),+ ConfigType.RIR: self.rirconfig_set.all(),+ ConfigType.MAXRIR: self.maxrirconfig_set.all(),+ ConfigType.REST: self.restconfig_set.all(),+ ConfigType.MAXREST: self.maxrestconfig_set.all(),+ ConfigType.SETS: self.setsconfig_set.all(),+ ConfigType.MAXSETS: self.maxsetsconfig_set.all(),+ }[config_type]++ return [c for c in configs if c.iteration <= iteration]@staticmethoddef calculate_config_value(configs: List[AbstractChangeConfig]) -> Decimal | None:@@ -407,17 +425,15 @@ class SlotEntry(models.Model):if max_weight and weight and max_weight > weightelse None,weight_rounding=self.weight_rounding if weight is not None else None,- # TODO: decide on whether to return None or always the unit- # weight_unit=self.weight_unit_id if weight is not None else None,- weight_unit=self.weight_unit_id,+ weight_unit=self.weight_unit_id if weight is not None else None,+ weight_unit_name=self.weight_unit.name if weight is not None else None,repetitions=round_value(repetitions, self.repetition_rounding),max_repetitions=round_value(max_repetitions, self.repetition_rounding)if max_repetitions and repetitions and max_repetitions > repetitionselse None,repetitions_rounding=self.repetition_rounding if repetitions is not None else None,- repetitions_unit=self.repetition_unit_id,- # TODO: decide on whether to return None or always the unit- # reps_unit=self.repetition_unit_id if reps is not None else None,+ repetitions_unit=self.repetition_unit_id if repetitions is not None else None,+ repetitions_unit_name=self.repetition_unit.name if repetitions is not None else None,rir=round_value(rir, 0.5),max_rir=round_value(max_rir, 0.5) if max_rir and rir and max_rir > rir else None,rest=round_value(rest, 1),diff --git a/wger/manager/signals.py b/wger/manager/signals.pyindex b7ca75dc0..d3d1e8bcf 100644--- a/wger/manager/signals.py+++ b/wger/manager/signals.py@@ -73,40 +73,6 @@ def update_cache_slot_entry(sender, instance: SlotEntry, **kwargs):def handle_config_change(sender, instance: AbstractChangeConfig, **kwargs):reset_routine_cache(instance.slot_entry.slot.day.routine)- update_has_progression_flag(instance)- update_object_cache(instance)---def update_has_progression_flag(instance: AbstractChangeConfig):- """- Update the has_progression flag on the slot entry- """- slot_entry = instance.slot_entry-- slot_entry.has_progression = any(- config_set.count() > 1- for config_set in [- slot_entry.weightconfig_set.all(),- slot_entry.maxweightconfig_set.all(),- slot_entry.repetitionsconfig_set.all(),- slot_entry.maxrepetitionsconfig_set.all(),- slot_entry.setsconfig_set.all(),- slot_entry.maxsetsconfig_set.all(),- slot_entry.restconfig_set.all(),- slot_entry.maxrestconfig_set.all(),- slot_entry.rirconfig_set.all(),- slot_entry.maxrirconfig_set.all(),- ]- )---def update_object_cache(instance: AbstractChangeConfig):- """- Update the has_progression flag on the slot entry- """-- slot_entry = instance.slot_entry- cache.delete(CacheKeyMapper.slot_entry_configs_objects_key(slot_entry.id, instance.iteration))def update_cache_log(sender, instance: WorkoutLog, **kwargs):diff --git a/wger/manager/tests/test_day.py b/wger/manager/tests/test_day.pyindex efb63b11f..6f4005748 100644--- a/wger/manager/tests/test_day.py+++ b/wger/manager/tests/test_day.py@@ -45,8 +45,12 @@ class DaySlotTestCase(WgerTestCase):exercise=1,weight=80,weight_rounding=Decimal('1.25'),+ weight_unit=1,+ weight_unit_name='kg',repetitions=4,repetitions_rounding=Decimal('1.00'),+ repetitions_unit=1,+ repetitions_unit_name='Repetitions',rir=None,rest=None,sets=1,@@ -56,8 +60,12 @@ class DaySlotTestCase(WgerTestCase):exercise=2,weight=20,weight_rounding=Decimal('1.25'),+ weight_unit=1,+ weight_unit_name='kg',repetitions=5,repetitions_rounding=Decimal('1.00'),+ repetitions_unit=1,+ repetitions_unit_name='Repetitions',rir=None,rest=None,sets=1,@@ -99,8 +107,12 @@ class DaySlotTestCase(WgerTestCase):exercise=1,weight=80,weight_rounding=Decimal('1.25'),+ weight_unit=1,+ weight_unit_name='kg',repetitions=Decimal(4),repetitions_rounding=Decimal('1.00'),+ repetitions_unit=1,+ repetitions_unit_name='Repetitions',rir=None,rest=None,sets=5,@@ -115,8 +127,12 @@ class DaySlotTestCase(WgerTestCase):exercise=2,weight=20,weight_rounding=Decimal('1.25'),+ weight_unit=1,+ weight_unit_name='kg',repetitions=5,repetitions_rounding=Decimal('1.00'),+ repetitions_unit=1,+ repetitions_unit_name='Repetitions',rir=None,rest=None,sets=2,@@ -136,8 +152,12 @@ class DaySlotTestCase(WgerTestCase):exercise=3,weight=80,weight_rounding=Decimal('1.25'),+ weight_unit=1,+ weight_unit_name='kg',repetitions=6,repetitions_rounding=Decimal('1.00'),+ repetitions_unit=1,+ repetitions_unit_name='Repetitions',rir=None,rest=None,sets=5,@@ -153,8 +173,12 @@ class DaySlotTestCase(WgerTestCase):exercise=3,weight=50,weight_rounding=Decimal('1.25'),+ weight_unit=1,+ weight_unit_name='kg',repetitions=4,repetitions_rounding=Decimal('1.00'),+ repetitions_unit=1,+ repetitions_unit_name='Repetitions',rir=None,rest=None,sets=3,diff --git a/wger/manager/tests/test_routine_statistics.py b/wger/manager/tests/test_routine_statistics.pyindex 74767d26a..0717811ed 100644--- a/wger/manager/tests/test_routine_statistics.py+++ b/wger/manager/tests/test_routine_statistics.py@@ -18,9 +18,9 @@ import datetime# wgerfrom wger.core.tests.base_testcase import WgerTestCasefrom wger.manager.consts import (- ID_UNIT_KG,- ID_UNIT_LB,- ID_UNIT_REPETITIONS,+ REP_UNIT_REPETITIONS,+ WEIGHT_UNIT_KG,+ WEIGHT_UNIT_LB,)from wger.manager.dataclasses import LogDatafrom wger.manager.models import WorkoutLog@@ -51,9 +51,9 @@ class RoutineStatisticsTestCase(WgerTestCase):user_id=1,routine=self.routine,date=datetime.date(2024, 2, 1),- repetitions_unit_id=ID_UNIT_REPETITIONS,+ repetitions_unit_id=REP_UNIT_REPETITIONS,repetitions=5,- weight_unit_id=ID_UNIT_KG,+ weight_unit_id=WEIGHT_UNIT_KG,weight=10,exercise_id=1,iteration=1,@@ -64,9 +64,9 @@ class RoutineStatisticsTestCase(WgerTestCase):user_id=1,routine=self.routine,date=datetime.date(2024, 2, 2),- repetitions_unit_id=ID_UNIT_REPETITIONS,+ repetitions_unit_id=REP_UNIT_REPETITIONS,repetitions=1,- weight_unit_id=ID_UNIT_KG,+ weight_unit_id=WEIGHT_UNIT_KG,weight=10,exercise_id=1,iteration=2,@@ -77,9 +77,9 @@ class RoutineStatisticsTestCase(WgerTestCase):user_id=1,routine=self.routine,date=datetime.date(2024, 2, 10),- repetitions_unit_id=ID_UNIT_REPETITIONS,+ repetitions_unit_id=REP_UNIT_REPETITIONS,repetitions=1,- weight_unit_id=ID_UNIT_KG,+ weight_unit_id=WEIGHT_UNIT_KG,weight=10,exercise_id=3,iteration=3,@@ -90,9 +90,9 @@ class RoutineStatisticsTestCase(WgerTestCase):user_id=1,routine=self.routine,date=datetime.date(2024, 2, 10),- repetitions_unit_id=ID_UNIT_REPETITIONS,+ repetitions_unit_id=REP_UNIT_REPETITIONS,repetitions=1,- weight_unit_id=ID_UNIT_LB,+ weight_unit_id=WEIGHT_UNIT_LB,weight=10,exercise_id=3,iteration=3,diff --git a/wger/manager/tests/test_set_config_data.py b/wger/manager/tests/test_set_config_data.pyindex bfb9879d0..fa38b4eca 100644--- a/wger/manager/tests/test_set_config_data.py+++ b/wger/manager/tests/test_set_config_data.py@@ -35,6 +35,7 @@ class SetConfigDataTestCase(WgerTestCase):repetitions_unit=1,weight=20,weight_unit=1,+ weight_unit_name='kg',rir=3,rest=None,)@@ -48,6 +49,7 @@ class SetConfigDataTestCase(WgerTestCase):def test_text_repr_weight_unit(self):self.config.weight_unit = 2+ self.config.weight_unit_name = 'lb'self.assertEqual(self.config.text_repr, '4 × 20 lb @ 3 RiR')def test_text_repr_no_rir(self):@@ -75,11 +77,13 @@ class SetConfigDataTestCase(WgerTestCase):def test_text_repr_reps_unit(self):self.config.repetitions = 90self.config.repetitions_unit = 3+ self.config.repetitions_unit_name = 'Seconds'self.assertEqual(self.config.text_repr, '90 Seconds × 20 kg @ 3 RiR')def test_text_repr_reps_unit_no_weight(self):self.config.repetitions = 90self.config.repetitions_unit = 3+ self.config.repetitions_unit_name = 'Seconds'self.config.weight = Noneself.assertEqual(self.config.text_repr, '90 Seconds @ 3 RiR')diff --git a/wger/manager/tests/test_slot_entry.py b/wger/manager/tests/test_slot_entry.pyindex cafe0f72c..3e148ced6 100644--- a/wger/manager/tests/test_slot_entry.py+++ b/wger/manager/tests/test_slot_entry.py@@ -175,93 +175,129 @@ class SlotEntryTestCase(WgerTestCase):repetitions=5,).save()- self.assertEqual(- self.slot_entry.get_config_data(1),- SetConfigData(- slot_entry_id=self.slot_entry.pk,- exercise=1,- sets=4,- weight=Decimal(80),- weight_rounding=Decimal(2.5),- repetitions=Decimal(4),- repetitions_rounding=2,- rir=Decimal(2),- rest=120,+ self.assertDictEqual(+ asdict(self.slot_entry.get_config_data(1)),+ asdict(+ SetConfigData(+ slot_entry_id=self.slot_entry.pk,+ exercise=1,+ sets=4,+ weight=Decimal(80),+ weight_rounding=Decimal(2.5),+ weight_unit=1,+ weight_unit_name='kg',+ repetitions=Decimal(4),+ repetitions_unit=1,+ repetitions_unit_name='Repetitions',+ repetitions_rounding=2,+ rir=Decimal(2),+ rest=120,+ )),)- self.assertEqual(- self.slot_entry.get_config_data(2),- SetConfigData(- slot_entry_id=self.slot_entry.pk,- exercise=1,- sets=4,- weight=Decimal(80),- weight_rounding=Decimal(2.5),- repetitions=Decimal(4),- repetitions_rounding=2,- rir=Decimal(2),- rest=120,+ self.assertDictEqual(+ asdict(self.slot_entry.get_config_data(2)),+ asdict(+ SetConfigData(+ slot_entry_id=self.slot_entry.pk,+ exercise=1,+ sets=4,+ weight=Decimal(80),+ weight_rounding=Decimal(2.5),+ weight_unit=1,+ weight_unit_name='kg',+ repetitions=Decimal(4),+ repetitions_unit=1,+ repetitions_unit_name='Repetitions',+ repetitions_rounding=2,+ rir=Decimal(2),+ rest=120,+ )),)- self.assertEqual(- self.slot_entry.get_config_data(3),- SetConfigData(- slot_entry_id=self.slot_entry.pk,- exercise=1,- sets=4,- weight=Decimal(80),- weight_rounding=Decimal('2.5'),- repetitions=Decimal(4),- repetitions_rounding=2,- rir=Decimal(2),- rest=120,+ self.assertDictEqual(+ asdict(self.slot_entry.get_config_data(3)),+ asdict(+ SetConfigData(+ slot_entry_id=self.slot_entry.pk,+ exercise=1,+ sets=4,+ weight=Decimal(80),+ weight_rounding=Decimal('2.5'),+ weight_unit=1,+ weight_unit_name='kg',+ repetitions=Decimal(4),+ repetitions_unit=1,+ repetitions_unit_name='Repetitions',+ repetitions_rounding=2,+ rir=Decimal(2),+ rest=120,+ )),)- self.assertEqual(- self.slot_entry.get_config_data(4),- SetConfigData(- slot_entry_id=self.slot_entry.pk,- exercise=1,- sets=4,- weight=Decimal(82.5),- weight_rounding=Decimal('2.5'),- repetitions=Decimal(4),- repetitions_rounding=2,- rir=Decimal(2),- rest=120,+ self.assertDictEqual(+ asdict(self.slot_entry.get_config_data(4)),+ asdict(+ SetConfigData(+ slot_entry_id=self.slot_entry.pk,+ exercise=1,+ sets=4,+ weight=Decimal(82.5),+ weight_rounding=Decimal('2.5'),+ weight_unit=1,+ weight_unit_name='kg',+ repetitions=Decimal(4),+ repetitions_rounding=2,+ repetitions_unit=1,+ repetitions_unit_name='Repetitions',+ rir=Decimal(2),+ rest=120,+ )),)- self.assertEqual(- self.slot_entry.get_config_data(5),- SetConfigData(- slot_entry_id=self.slot_entry.pk,- exercise=1,- sets=4,- weight=Decimal('42.5'),- weight_rounding=Decimal('2.5'),- repetitions=Decimal(4),- repetitions_rounding=2,- rir=Decimal(2),- rest=120,+ self.assertDictEqual(+ asdict(self.slot_entry.get_config_data(5)),+ asdict(+ SetConfigData(+ slot_entry_id=self.slot_entry.pk,+ exercise=1,+ sets=4,+ weight=Decimal('42.5'),+ weight_rounding=Decimal('2.5'),+ weight_unit=1,+ weight_unit_name='kg',+ repetitions=Decimal(4),+ repetitions_rounding=2,+ repetitions_unit=1,+ repetitions_unit_name='Repetitions',+ rir=Decimal(2),+ rest=120,+ )),)- self.assertEqual(- self.slot_entry.get_config_data(6),- SetConfigData(- slot_entry_id=self.slot_entry.pk,- exercise=1,- sets=4,- weight=Decimal(42.5),- weight_rounding=Decimal('2.5'),- repetitions=Decimal(4),- repetitions_rounding=2,- rir=Decimal(2),- rest=120,+ self.assertDictEqual(+ asdict(self.slot_entry.get_config_data(6)),+ asdict(+ SetConfigData(+ slot_entry_id=self.slot_entry.pk,+ exercise=1,+ sets=4,+ weight=Decimal(42.5),+ weight_rounding=Decimal('2.5'),+ weight_unit=1,+ weight_unit_name='kg',+ repetitions=Decimal(4),+ repetitions_rounding=2,+ repetitions_unit=1,+ repetitions_unit_name='Repetitions',+ rir=Decimal(2),+ rest=120,+ )),)@@ -269,7 +305,6 @@ class SlotEntryTestCase(WgerTestCase):"""Test that the sets are correctly calculated if there are requirements"""-self.slot_entry.weight_rounding = 2.5self.slot_entry.repetition_rounding = 2self.slot_entry.save()@@ -314,28 +349,36 @@ class SlotEntryTestCase(WgerTestCase):).save()self.assertDictEqual(- self.slot_entry.get_config_data(1).__dict__,- SetConfigData(- slot_entry_id=self.slot_entry.pk,- exercise=1,- sets=5,- weight=Decimal(50),- weight_rounding=Decimal(2.5),- rest=Decimal(90),- ).__dict__,+ asdict(self.slot_entry.get_config_data(1)),+ asdict(+ SetConfigData(+ slot_entry_id=self.slot_entry.pk,+ exercise=1,+ sets=5,+ weight=Decimal(50),+ weight_rounding=Decimal(2.5),+ weight_unit=1,+ weight_unit_name='kg',+ rest=Decimal(90),+ )+ ),)# Sets did increaseself.assertDictEqual(- self.slot_entry.get_config_data(2).__dict__,- SetConfigData(- slot_entry_id=self.slot_entry.pk,- exercise=1,- sets=6,- weight=Decimal(50),- weight_rounding=Decimal(2.5),- rest=Decimal(90),- ).__dict__,+ asdict(self.slot_entry.get_config_data(2)),+ asdict(+ SetConfigData(+ slot_entry_id=self.slot_entry.pk,+ exercise=1,+ sets=6,+ weight=Decimal(50),+ weight_rounding=Decimal(2.5),+ weight_unit=1,+ weight_unit_name='kg',+ rest=Decimal(90),+ )+ ),)def test_requirements_sets_unmet(self):@@ -394,6 +437,8 @@ class SlotEntryTestCase(WgerTestCase):sets=5,weight=Decimal(50),weight_rounding=Decimal(2.5),+ weight_unit=1,+ weight_unit_name='kg',rest=90,),)@@ -407,6 +452,8 @@ class SlotEntryTestCase(WgerTestCase):sets=5,weight=Decimal(50),weight_rounding=Decimal(2.5),+ weight_unit=1,+ weight_unit_name='kg',rest=90,),)@@ -465,11 +512,15 @@ class SlotEntryTestCase(WgerTestCase):exercise=1,sets=1,weight=Decimal(80),+ weight_unit=1,+ weight_unit_name='kg',max_weight=Decimal(100),weight_rounding=Decimal('2.5'),repetitions=Decimal(4),- max_repetitions=Decimal(6),repetitions_rounding=2,+ repetitions_unit=1,+ repetitions_unit_name='Repetitions',+ max_repetitions=Decimal(6),rir=None,rest=None,),@@ -482,11 +533,15 @@ class SlotEntryTestCase(WgerTestCase):exercise=1,sets=1,weight=Decimal(80),+ weight_unit=1,+ weight_unit_name='kg',max_weight=Decimal(100),weight_rounding=Decimal('2.5'),repetitions=Decimal(4),- max_repetitions=Decimal(6),+ repetitions_unit=1,+ repetitions_unit_name='Repetitions',repetitions_rounding=2,+ max_repetitions=Decimal(6),rir=None,rest=None,),@@ -529,22 +584,23 @@ class SlotEntryTestCase(WgerTestCase):"""Test that the correct config is calculated if there are no configs at all"""-- self.assertEqual(- self.slot_entry.get_config_data(1),- SetConfigData(- slot_entry_id=self.slot_entry.pk,- exercise=1,- sets=1,- max_sets=None,- weight=None,- weight_rounding=None,- weight_unit=1,- repetitions=None,- repetitions_rounding=None,- repetitions_unit=1,- rir=None,- rest=None,+ self.assertDictEqual(+ asdict(self.slot_entry.get_config_data(1)),+ asdict(+ SetConfigData(+ slot_entry_id=self.slot_entry.pk,+ exercise=1,+ sets=1,+ max_sets=None,+ weight=None,+ weight_rounding=None,+ weight_unit=None,+ repetitions=None,+ repetitions_rounding=None,+ repetitions_unit=None,+ rir=None,+ rest=None,+ )),)@@ -557,22 +613,6 @@ class SlotEntryTestCase(WgerTestCase):self.assertTrue(self.slot_entry.has_progression)- def test_cache_load_all_configs(self):- """Tests that cache used in load_all_configs is correctly (re)set"""-- key = CacheKeyMapper.slot_entry_configs_objects_key(self.slot_entry.pk, 1)-- set_config = SetsConfig(slot_entry=self.slot_entry, iteration=1, value=4)- set_config.save()-- self.assertIsNone(cache.get(key))- self.slot_entry.load_all_configs(1)- self.assertTrue(cache.get(key))-- set_config.value = 5- set_config.save()- self.assertIsNone(cache.get(key))-def test_cache_get_config_data(self):"""Tests that cache used in get_config_data is correctly (re)set"""diff --git a/wger/utils/cache.py b/wger/utils/cache.pyindex bb089fefa..3ecd7e1b5 100644--- a/wger/utils/cache.py+++ b/wger/utils/cache.py@@ -19,6 +19,7 @@ import loggingfrom django.core.cache import cachefrom django.core.cache.utils import make_template_fragment_key+logger = logging.getLogger(__name__)@@ -93,24 +94,24 @@ class CacheKeyMapper:return f'routine-date-sequence-{id}'@classmethod- def get_routine_api_date_sequence_key(cls, id: int):- return f'routine-api-date-sequence-display-{id}'+ def routine_api_date_sequence_display_key(cls, pk: int):+ return f'routine-api-date-sequence-display-{pk}'@classmethod- def get_routine_api_stats(cls, id: int):- return f'routine-api-stats-{id}'+ def routine_api_date_sequence_gym_key(cls, pk: int):+ return f'routine-api-date-sequence-gym-{pk}'@classmethod- def get_routine_api_structure_key(cls, id: int):- return f'routine-api-structure-{id}'+ def get_routine_api_stats(cls, pk: int):+ return f'routine-api-stats-{pk}'@classmethod- def slot_entry_configs_key(cls, id: int):- return f'slot-entry-configs-{id}'+ def get_routine_api_structure_key(cls, pk: int):+ return f'routine-api-structure-{pk}'@classmethod- def slot_entry_configs_objects_key(cls, slot_entry_id: int, iteration: int):- return f'slot-entry-configs-dict-{slot_entry_id}-{iteration}'+ def slot_entry_configs_key(cls, pk: int):+ return f'slot-entry-configs-{pk}'cache_mapper = CacheKeyMapper()