Self hosted FLOSS fitness/workout, nutrition and weight tracker
Change primary key type for Category and Measurement models to UUID
Roland Geiderfa0b30c9703d
diff --git a/.dockerignore b/.dockerignoreindex a8a95f1bb..40235a0ee 100644--- a/.dockerignore+++ b/.dockerignore@@ -28,7 +28,6 @@ venv/db//dist//node_modules/-/wger.egg-info/npm-debug.log*/extras/open-food-facts/dump//extras/authors/commits_cache/diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 23741e000..766566d13 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,19 @@# Changelog for the next release+## Powersync++Adds powersync support. This allows clients (i.e. the mobile app) to finally+implement offline support. The data is saved in a local sqlite database and+synced with the server when possible.++Incompatible changes:++The type for the ID for Measurement and MeasurementCategory was changed from integer+to UUID. This was made to allow for clients to generate IDs locally and affects+`/api/v2/measurement-category/` and `/api/v2/measurement/`.++## Others+<https://github.com/wger-project/wger/issues/2231> Add vegan and vegetarian flags tothe ingredient model. This allows to filter products based on dietary preferences.The unused `/api/v2/ingredient/search/` API endpoint has been removed.diff --git a/wger/core/api/views.py b/wger/core/api/views.pyindex 083d0682f..10c7718ce 100644--- a/wger/core/api/views.py+++ b/wger/core/api/views.py@@ -516,7 +516,7 @@ def upload_powersync_data(request):ps_weight.handle_delete(payload=data['data'], user_id=user_id)# Measurements- case 'measurement_category':+ case 'measurements_category':if http_verb == 'PUT':ps_measurements.handle_create_category(payload=data['data'], user_id=user_id)elif http_verb == 'PATCH':@@ -524,7 +524,7 @@ def upload_powersync_data(request):elif http_verb == 'DELETE':ps_measurements.handle_delete_category(payload=data['data'], user_id=user_id)- case 'measurement_measurement':+ case 'measurements_measurement':if http_verb == 'PUT':ps_measurements.handle_create_measurement(payload=data['data'], user_id=user_id)elif http_verb == 'PATCH':diff --git a/wger/measurements/migrations/0004_change_category_pk_type_to_uuid.py b/wger/measurements/migrations/0004_change_category_pk_type_to_uuid.pynew file mode 100644index 000000000..a75e6268c--- /dev/null+++ b/wger/measurements/migrations/0004_change_category_pk_type_to_uuid.py@@ -0,0 +1,108 @@+# Generated by Django 5.2.12 on 2026-03-15 11:29++"""+This migration replaces the integer Primary Key of the Category model with a UUID.++Since this is not directly possible, the following steps are taken:++1. Add a temporary UUID field (`category_tmp`) to Measurement and populate it with+ existing related category UUIDs.+2. Remove the old integer `category` ForeignKey.+3. Switch the Category model's Primary Key from `id` to `uuid`.+4. Restore `Measurement.category` as a ForeignKey (pointing to the new UUID PK).+5. Rename `Category.uuid` to `id` (while keeping the UUID type).+"""++from wger.utils.uuid import uuid7+from django.db import migrations, models+from django.db.migrations.state import StateApps+from django.db.models import Subquery, OuterRef+++def populate_category_tmp(apps: StateApps, schema_editor):+ Measurement = apps.get_model('measurements', 'Measurement')+ Category = apps.get_model('measurements', 'Category')++ Measurement.objects.update(+ category_tmp=Subquery(+ Category.objects.filter(id=OuterRef('category')).values('uuid')[:1],+ )+ )+++def reverse_populate_category_tmp(apps: StateApps, schema_editor):+ Measurement = apps.get_model('measurements', 'Measurement')+ for m in Measurement.objects.all():+ m.category_tmp = None+ m.save(update_fields=['category_tmp'])+++class Migration(migrations.Migration):+ dependencies = [+ ('measurements', '0003_add_uuids'),+ ]++ operations = [+ # Add tmp UUID field and copy the category UUIDs into it.+ migrations.AddField(+ model_name='measurement',+ name='category_tmp',+ field=models.UUIDField(editable=False, null=True),+ ),+ migrations.RunPython(populate_category_tmp, reverse_populate_category_tmp),+ # Remove old FK+ migrations.AlterUniqueTogether(+ name='measurement',+ unique_together=set(),+ ),+ migrations.RemoveField(+ model_name='measurement',+ name='category',+ ),+ # Change category PK+ migrations.RemoveField(+ model_name='category',+ name='id',+ ),+ migrations.AlterField(+ model_name='category',+ name='uuid',+ field=models.UUIDField(+ default=uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ # Rename "category_tmp" back to "category"+ migrations.RenameField(+ model_name='measurement',+ old_name='category_tmp',+ new_name='category',+ ),+ migrations.AlterUniqueTogether(+ name='measurement',+ unique_together={('date', 'category')},+ ),+ # Make category+ migrations.AlterField(+ model_name='measurement',+ name='category',+ field=models.UUIDField(db_column='category_id', editable=False, null=True),+ ),+ # Change the FK and rename+ migrations.AlterField(+ model_name='measurement',+ name='category',+ field=models.ForeignKey(+ on_delete=models.deletion.CASCADE,+ to='measurements.category',+ verbose_name='Category',+ ),+ ),+ migrations.RenameField(+ model_name='category',+ old_name='uuid',+ new_name='id',+ ),+ ]diff --git a/wger/measurements/migrations/0005_change_measurement_pk_to_uuid.py b/wger/measurements/migrations/0005_change_measurement_pk_to_uuid.pynew file mode 100644index 000000000..f6fb9ef24--- /dev/null+++ b/wger/measurements/migrations/0005_change_measurement_pk_to_uuid.py@@ -0,0 +1,33 @@+# Generated by Django 5.2.12 on 2026-03-15 12:21++from django.db import migrations, models+from wger.utils.uuid import uuid7+++class Migration(migrations.Migration):+ dependencies = [+ ('measurements', '0004_change_category_pk_type_to_uuid'),+ ]++ operations = [+ migrations.RemoveField(+ model_name='measurement',+ name='id',+ ),+ migrations.RenameField(+ model_name='measurement',+ old_name='uuid',+ new_name='id',+ ),+ migrations.AlterField(+ model_name='measurement',+ name='id',+ field=models.UUIDField(+ default=uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ unique=True,+ ),+ ),+ ]diff --git a/wger/measurements/models/category.py b/wger/measurements/models/category.pyindex 1afea33ba..dda144f72 100644--- a/wger/measurements/models/category.py+++ b/wger/measurements/models/category.py@@ -20,6 +20,9 @@ import uuidfrom django.contrib.auth.models import Userfrom django.db import models+# wger+from wger.utils.uuid import uuid7+class Category(models.Model):class Meta:@@ -27,19 +30,19 @@ class Category(models.Model):'-name',]+ id = models.UUIDField(+ default=uuid7,+ editable=False,+ null=False,+ primary_key=True,+ )+user = models.ForeignKey(User,verbose_name='User',on_delete=models.CASCADE,)- uuid = models.UUIDField(- default=uuid.uuid4,- editable=False,- null=False,- unique=True,- )-name = models.CharField(verbose_name='Name',max_length=100,diff --git a/wger/measurements/models/measurement.py b/wger/measurements/models/measurement.pyindex 29d00633e..a48288f04 100644--- a/wger/measurements/models/measurement.py+++ b/wger/measurements/models/measurement.py@@ -27,6 +27,7 @@ from django.db import models# wgerfrom wger.measurements.models import Category+from wger.utils.uuid import uuid7class Measurement(models.Model):@@ -36,17 +37,18 @@ class Measurement(models.Model):'-date',]- category = models.ForeignKey(- Category,- verbose_name='User',- on_delete=models.CASCADE,- )-- uuid = models.UUIDField(- default=uuid.uuid4,+ id = models.UUIDField(+ default=uuid7,editable=False,null=False,unique=True,+ primary_key=True,+ )++ category = models.ForeignKey(+ Category,+ verbose_name='Category',+ on_delete=models.CASCADE,)date = models.DateField(diff --git a/wger/measurements/powersync.py b/wger/measurements/powersync.pyindex e903db39b..bcfdda0c8 100644--- a/wger/measurements/powersync.py+++ b/wger/measurements/powersync.py@@ -32,7 +32,7 @@ logger = logging.getLogger(__name__)def handle_update_category(payload: dict[str, Any], user_id: int) -> None:"""Handle a push event from PowerSync"""logger.debug(f'Received PowerSync payload for update: {payload}')- entry = Category.objects.get(uuid=payload['id'], user_id=user_id)+ entry = Category.objects.get(pk=payload['id'], user_id=user_id)if not entry:logger.warning(@@ -43,7 +43,7 @@ def handle_update_category(payload: dict[str, Any], user_id: int) -> None:serializer = CategorySerializer(entry, data=payload, partial=True)if serializer.is_valid():serializer.save()- logger.info(f'Updated Category {entry.pk} (uuid={entry.uuid}) for user {user_id}')+ logger.info(f'Updated Category {entry.pk} for user {user_id}')else:logger.warning(f'PowerSync update validation failed: {serializer.errors}')@@ -63,7 +63,7 @@ def handle_create_category(payload: dict[str, Any], user_id: int) -> None:def handle_delete_category(payload: dict[str, Any], user_id: int) -> None:"""Handle a delete event from PowerSync"""logger.debug(f'Received PowerSync payload for delete: {payload}')- entry = Category.objects.get(uuid=payload['id'], user_id=user_id)+ entry = Category.objects.get(pk=payload['id'], user_id=user_id)if not entry:logger.warning(f'Category with UUID {payload["id"]} not found for delete.')return@@ -73,7 +73,7 @@ def handle_delete_category(payload: dict[str, Any], user_id: int) -> None:def handle_update_measurement(payload: dict[str, Any], user_id: int) -> None:"""Handle a push event from PowerSync"""logger.debug(f'Received PowerSync payload for update: {payload}')- entry = Measurement.objects.get(uuid=payload['id'], user_id=user_id)+ entry = Measurement.objects.get(pk=payload['id'], user_id=user_id)if not entry:logger.warning(@@ -84,7 +84,7 @@ def handle_update_measurement(payload: dict[str, Any], user_id: int) -> None:serializer = MeasurementSerializer(entry, data=payload, partial=True)if serializer.is_valid():serializer.save()- logger.info(f'Updated Measurement {entry.pk} (uuid={entry.uuid}) for user {user_id}')+ logger.info(f'Updated Measurement {entry.pk} for user {user_id}')else:logger.warning(f'PowerSync update validation failed: {serializer.errors}')@@ -102,7 +102,7 @@ def handle_create_measurement(payload: dict[str, Any], user_id: int) -> None:def handle_delete_measurement(payload: dict[str, Any], user_id: int) -> None:"""Handle a delete event from PowerSync"""logger.debug(f'Received PowerSync payload for delete: {payload}')- entry = Measurement.objects.get(uuid=payload['id'], user_id=user_id)+ entry = Measurement.objects.get(pk=payload['id'], user_id=user_id)if not entry:logger.warning(f'Measurement with UUID {payload["id"]} not found for delete.')returndiff --git a/wger/utils/tests/test_uuid.py b/wger/utils/tests/test_uuid.pynew file mode 100644index 000000000..e83bc3e84--- /dev/null+++ b/wger/utils/tests/test_uuid.py@@ -0,0 +1,52 @@+# This file is part of wger Workout Manager.+#+# wger 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.+#+# This program 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/>.++# Standard Library+import time++# Django+from django.test import TestCase++# wger+from wger.utils.uuid import uuid7+++class UUID7TestCase(TestCase):+ def test_version(self):+ """+ Check if the generated UUIDs have the correct version.+ """+ uuid_obj = uuid7()+ self.assertEqual(uuid_obj.version, 7)++ def test_monotonicity(self):+ """+ Check if the generated UUIDs are monotonic (increasing).+ """+ uuids = []+ for _ in range(10):+ uuids.append(uuid7())++ # Wait 5ms to ensure timestamp increases+ time.sleep(0.005)++ # Check values+ for i in range(len(uuids) - 1):+ self.assertLess(uuids[i], uuids[i + 1])++ # Check string representation sort order+ str_uuids = [str(u) for u in uuids]+ sorted_str_uuids = sorted(str_uuids)+ self.assertEqual(str_uuids, sorted_str_uuids)diff --git a/wger/utils/uuid.py b/wger/utils/uuid.pynew file mode 100644index 000000000..210a55279--- /dev/null+++ b/wger/utils/uuid.py@@ -0,0 +1,62 @@+# This file is part of wger Workout Manager.+#+# wger 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.+#+# This program 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/>.++# Standard Library+import os+import time+import uuid as py_uuid+++def uuid7() -> py_uuid.UUID:+ """+ NOTE: this is only needed because currently there isn't a UUIDv7 implementation+ in the python standard library. Once that becomes available, this function can+ be deleted and its uses replaced.++ Generate a UUIDv7.++ Layout:+ - 48 bits: Unix timestamp in milliseconds+ - 12 bits: Random data (or sequence counter if strict monotonicity is needed)+ - 2 bits: Variant (set to 0b10)+ - 4 bits: Version (set to 0b0111)+ - 62 bits: Random data+ """++ # Get current time in milliseconds+ timestamp_ms = int(time.time() * 1000)+ b = list(os.urandom(16))++ # Fill timestamp (big-endian)+ b[0] = (timestamp_ms >> 40) & 0xFF+ b[1] = (timestamp_ms >> 32) & 0xFF+ b[2] = (timestamp_ms >> 24) & 0xFF+ b[3] = (timestamp_ms >> 16) & 0xFF+ b[4] = (timestamp_ms >> 8) & 0xFF+ b[5] = timestamp_ms & 0xFF++ # Set version (nibble 12, index 6)+ # version 7 => 0111+ # current byte value: vvvvrrrr+ # destination: 0111rrrr+ b[6] = (b[6] & 0x0F) | 0x70++ # Set variant (nibble 16, index 8)+ # variant 10 => 10+ # current byte value: vvvrrrrr+ # destination: 10xr rrrr+ b[8] = (b[8] & 0x3F) | 0x80++ return py_uuid.UUID(bytes=bytes(b))diff --git a/wger/weight/models.py b/wger/weight/models.pyindex e50bddfe8..eb52863d4 100644--- a/wger/weight/models.py+++ b/wger/weight/models.py@@ -28,8 +28,6 @@ from django.db import modelsfrom django.utils.translation import gettext_lazy as _--class WeightEntry(models.Model):"""Model for a weight point