Self hosted FLOSS fitness/workout, nutrition and weight tracker
Add dynamic type enums and extendable dynamic measurement behaviour
Dylan Smith87ba14c29cc9
diff --git a/wger/measurements/api/serializers.py b/wger/measurements/api/serializers.pyindex 9643b4fe4..3dd10b56f 100644--- a/wger/measurements/api/serializers.py+++ b/wger/measurements/api/serializers.py@@ -33,7 +33,7 @@ class UnitSerializer(serializers.ModelSerializer):class Meta:model = Category- fields = ('id', 'name', 'unit', 'is_dynamic')+ fields = ('id', 'name', 'unit', 'dynamic_type')class MeasurementSerializer(serializers.ModelSerializer):diff --git a/wger/measurements/api/views.py b/wger/measurements/api/views.pyindex d62a5d20c..b628458d4 100644--- a/wger/measurements/api/views.py+++ b/wger/measurements/api/views.py@@ -42,7 +42,7 @@ from wger.utils.viewsets import WgerOwnerObjectModelViewSetlogger = logging.getLogger(__name__)-def calculate_bmi(user):+def calculate_bmi(user, category_id):from wger.weight.models import WeightEntryprofile = getattr(user, 'userprofile', None)@@ -56,16 +56,21 @@ def calculate_bmi(user):return [{- 'id': f'bmi-{w.id}',- 'category': -1,- 'date': w.date,- # Cast w.weight to float to avoid the Decimal/Float TypeError+ 'id': w.id, # Use integer IDs so the frontend state manager doesn't complain+ 'category': int(category_id), # Link it to the requested category+ 'date': w.date.isoformat() if hasattr(w.date, 'isoformat') else w.date,'value': round(float(w.weight) / height_sq, 2),'notes': 'Auto-calculated from weight entry'}for w in weights]+# Map the dynamic_type enum to the math function+DYNAMIC_REGISTRY = {+ Category.DynamicType.BMI: calculate_bmi,+ # add squat 1rm later+}+class CategoryViewSet(WgerOwnerObjectModelViewSet):"""API endpoint for measurement units@@ -99,22 +104,18 @@ class CategoryViewSet(WgerOwnerObjectModelViewSet):"""return [(User, 'user')]- @action(detail=False, methods=['get'])- def dynamic(self, request):+ @action(detail=False, methods=['get'], url_path='dynamic-types')+ def dynamic_types(self, request):"""Dedicated route for virtual/calculated categories- URL: /api/v2/measurement-category/dynamic/+ Returns a list of available dynamic calculation types from the model Enum.+ URL: /api/v2/measurement-category/dynamic-types/"""- data = [- {- 'id': -1,- 'name': 'BMI',- 'unit': 'kg/m²',- 'is_dynamic': True- }- # easy to append more objects here later+ choices = [+ {"value": choice.value, "label": choice.label}+ for choice in Category.DynamicType]- return Response(data)+ return Response(choices)class MeasurementViewSet(WgerOwnerObjectModelViewSet):@@ -149,18 +150,26 @@ class MeasurementViewSet(WgerOwnerObjectModelViewSet):Intercept requests for dynamic categories before the filterset blocks them"""category_id = request.query_params.get('category')- is_dynamic = request.query_params.get('is_dynamic')-- print(request.query_params)- print("is_dynamic", is_dynamic)-- if category_id == '19':- bmi_data = calculate_bmi(request.user)- return Response({- "count": len(bmi_data),- "next": None,- "previous": None,- "results": bmi_data- })++ if category_id:+ try:+ # look up the category and check its enum value+ category = Category.objects.get(id=category_id, user=request.user)++ if category.dynamic_type != Category.DynamicType.NONE:+ calc_func = DYNAMIC_REGISTRY.get(category.dynamic_type)++ if calc_func:+ # execute the math function and wrap it in the DRF pagination envelope+ data = calc_func(request.user, category_id)+ return Response({+ "count": len(data),+ "next": None,+ "previous": None,+ "results": data+ })+ except (Category.DoesNotExist, ValueError):+ # fallback to standard behavior+ passreturn super().list(request, *args, **kwargs)\ No newline at end of filediff --git a/wger/measurements/migrations/0005_remove_category_is_dynamic_category_dynamic_type.py b/wger/measurements/migrations/0005_remove_category_is_dynamic_category_dynamic_type.pynew file mode 100644index 000000000..e0b3c0dd1--- /dev/null+++ b/wger/measurements/migrations/0005_remove_category_is_dynamic_category_dynamic_type.py@@ -0,0 +1,22 @@+# Generated by Django 5.2.14 on 2026-05-12 08:37++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ('measurements', '0004_category_is_dynamic'),+ ]++ operations = [+ migrations.RemoveField(+ model_name='category',+ name='is_dynamic',+ ),+ migrations.AddField(+ model_name='category',+ name='dynamic_type',+ field=models.CharField(choices=[('NONE', 'None'), ('BMI', 'Bmi'), ('SQUAT_1RM', 'Squat 1Rm')], db_index=True, default='NONE', max_length=20),+ ),+ ]diff --git a/wger/measurements/models/category.py b/wger/measurements/models/category.pyindex 845f9a9fb..dd001788e 100644--- a/wger/measurements/models/category.py+++ b/wger/measurements/models/category.py@@ -41,10 +41,16 @@ class Category(models.Model):max_length=30,)- is_dynamic = models.BooleanField(- verbose_name='Is Dynamic',- default=False,- help_text='Indicates if this category is automatically calculated.',+ class DynamicType(models.TextChoices):+ NONE = 'NONE',+ BMI = 'BMI',+ # SQUAT_1RM = 'SQUAT_1RM', can be added in future++ dynamic_type = models.CharField(+ max_length=20,+ choices=DynamicType.choices,+ default=DynamicType.NONE,+ db_index=True)def get_owner_object(self):