Self hosted FLOSS fitness/workout, nutrition and weight tracker
Properly delte the old weight entry table
Roland Geidera47e16d9b3a5
diff --git a/wger/core/tests/base_testcase.py b/wger/core/tests/base_testcase.pyindex fa27ce000..32e4c22d7 100644--- a/wger/core/tests/base_testcase.py+++ b/wger/core/tests/base_testcase.py@@ -115,7 +115,6 @@ class BaseTestCase:'test-gym-user-documents','test-contracts','test-apikeys',- 'test-weight-data','test-equipment','test-categories','test-muscles',diff --git a/wger/gallery/views/images.py b/wger/gallery/views/images.pyindex 045fb074d..43e8071fa 100644--- a/wger/gallery/views/images.py+++ b/wger/gallery/views/images.py@@ -67,7 +67,7 @@ class ImageAddView(WgerFormMixin, CreateView):"""Set the initial data for the form.- Read the comment on weight/models.py WeightEntry about why we need+ Read the note on manager.models.WorkoutSession.user about why we needto pass the user here."""return {'user': self.request.user, 'date': datetime.today()}diff --git a/wger/manager/models/session.py b/wger/manager/models/session.pyindex 6d74cd361..0d438d819 100644--- a/wger/manager/models/session.py+++ b/wger/manager/models/session.py@@ -51,7 +51,12 @@ class WorkoutSession(models.Model):"""The user the workout session belongs to- See note in weight.models.WeightEntry about why this is not editable=False+ NOTE: this field is neither marked as editable=False nor excluded from the+ form. This is done intentionally because otherwise it's *very* difficult+ and ugly to validate the uniqueness of unique_together fields when one+ field is excluded from the form. This does not pose any security risk+ because the value from the form is ignored and the request's user always+ used."""id = models.UUIDField(diff --git a/wger/weight/fixtures/test-weight-data.json b/wger/weight/fixtures/test-weight-data.jsondeleted file mode 100644index cc0b05083..000000000--- a/wger/weight/fixtures/test-weight-data.json+++ /dev/null@@ -1,72 +0,0 @@-[- {- "pk": 1,- "model": "weight.weightentry",- "fields": {- "uuid": "11111111-1111-1111-1111-000000000001",- "user": 2,- "weight": 77,- "date": "2012-10-01T14:30:21.592Z"- }- },- {- "pk": 2,- "model": "weight.weightentry",- "fields": {- "uuid": "11111111-1111-1111-1111-000000000002",- "user": 2,- "weight": 77.2,- "date": "2012-10-10T14:30:21.592Z"- }- },- {- "pk": 3,- "model": "weight.weightentry",- "fields": {- "uuid": "11111111-1111-1111-1111-000000000003",- "user": 2,- "weight": 80.6,- "date": "2012-11-01T14:30:21.592Z"- }- },- {- "pk": 4,- "model": "weight.weightentry",- "fields": {- "uuid": "11111111-1111-1111-1111-000000000004",- "user": 2,- "weight": 80,- "date": "2013-01-01T14:30:21.592Z"- }- },- {- "pk": 5,- "model": "weight.weightentry",- "fields": {- "uuid": "11111111-1111-1111-1111-000000000005",- "user": 2,- "weight": 81,- "date": "2013-01-10T14:30:21.592Z"- }- },- {- "pk": 6,- "model": "weight.weightentry",- "fields": {- "uuid": "11111111-1111-1111-1111-000000000006",- "user": 2,- "weight": 82,- "date": "2013-01-20T14:30:21.592Z"- }- },- {- "pk": 7,- "model": "weight.weightentry",- "fields": {- "uuid": "11111111-1111-1111-1111-000000000007",- "user": 2,- "weight": 83,- "date": "2013-01-30T14:30:21.592Z"- }- }-]diff --git a/wger/weight/migrations/0006_delete_weightentry.py b/wger/weight/migrations/0006_delete_weightentry.pynew file mode 100644index 000000000..6a1e96c95--- /dev/null+++ b/wger/weight/migrations/0006_delete_weightentry.py@@ -0,0 +1,68 @@+from django.db import migrations++from wger.utils.constants import TWOPLACES+from wger.utils.units import AbstractWeight++BATCH_SIZE = 2000+++def restore_weight_entries(apps, schema_editor):+ """+ Rebuild the WeightEntry table from the official body-weight categories+ so that measurements.0007 can be reverted afterwards.++ WeightEntry stores values in the user's preferred weight unit, so+ entries stamped with a different unit are converted back. Measurement+ ids become the WeightEntry uuids again, mirroring the forward backfill+ in measurements.0007.+ """+ WeightEntry = apps.get_model('weight', 'WeightEntry')+ Measurement = apps.get_model('measurements', 'Measurement')+ UserProfile = apps.get_model('core', 'UserProfile')++ unit_by_user = dict(UserProfile.objects.values_list('user_id', 'weight_unit'))++ batch = []+ entries = Measurement.objects.filter(+ category__metric_type='body_weight',+ category__is_official=True,+ ).select_related('category')+ for measurement in entries.iterator():+ user_id = measurement.category.user_id+ profile_unit = unit_by_user.get(user_id) or 'kg'+ entry_unit = measurement.extra_data.get('unit') or measurement.category.unit+ value = measurement.value+ if entry_unit != profile_unit and entry_unit in ('kg', 'lb'):+ weight = AbstractWeight(value, entry_unit)+ value = (weight.kg if profile_unit == 'kg' else weight.lb).quantize(TWOPLACES)++ batch.append(+ WeightEntry(+ uuid=measurement.id,+ user_id=user_id,+ date=measurement.date,+ weight=value,+ )+ )+ if len(batch) >= BATCH_SIZE:+ WeightEntry.objects.bulk_create(batch)+ batch = []+ WeightEntry.objects.bulk_create(batch)+++class Migration(migrations.Migration):+ dependencies = [+ ('weight', '0005_add_uuid'),+ # The forward backfill in measurements.0007 reads this table, so it+ # may only be dropped afterwards. On a full rollback this ordering+ # also runs the restore here before measurements.0007 deletes the+ # official categories.+ ('measurements', '0007_official_categories'),+ ]++ operations = [+ # Listed before DeleteModel so that the reverse recreates the table+ # first and then repopulates it+ migrations.RunPython(migrations.RunPython.noop, restore_weight_entries),+ migrations.DeleteModel(name='WeightEntry'),+ ]diff --git a/wger/weight/models.py b/wger/weight/models.pydeleted file mode 100644index 759957547..000000000--- a/wger/weight/models.py+++ /dev/null@@ -1,91 +0,0 @@-# This file is part of wger Workout Manager <https://github.com/wger-project>.-# Copyright (C) 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-from decimal import Decimal--# Django-from django.contrib.auth.models import User-from django.core.validators import (- MaxValueValidator,- MinValueValidator,-)-from django.db import models--# wger-from wger.utils.uuid import uuid7---class WeightEntry(models.Model):- """- Model for a weight point-- DEPRECATED (wger#2328): new weight data is written to- measurements.Measurement under the user's official 'body_weight'- """-- uuid = models.UUIDField(- default=uuid7,- editable=True,- null=False,- unique=True,- )-- date = models.DateTimeField(verbose_name='Date')- weight = models.DecimalField(- verbose_name='Weight',- max_digits=5,- decimal_places=2,- validators=[MinValueValidator(Decimal(30)), MaxValueValidator(Decimal(600))],- )-- user = models.ForeignKey(- User,- verbose_name='User',- on_delete=models.CASCADE,- )- """- The user the weight entry belongs to.-- NOTE: this field is neither marked as editable false nor is it excluded in- the form. This is done intentionally because otherwise it's *very* difficult- and ugly to validate the uniqueness of unique_together fields and one field- is excluded from the form. This does not pose any security risk because the- value from the form is ignored and the request's user always used.- """-- class Meta:- """- Metaclass to set some other properties- """-- verbose_name = 'Weight entry'- ordering = [- 'date',- ]- get_latest_by = 'date'-- def __str__(self):- """- Return a more human-readable representation- """- return '{0}: {1:.2f} kg'.format(self.date, self.weight)-- def get_owner_object(self):- """- Returns the object that has owner information- """- return selfdiff --git a/wger/weight/tests/test_entry.py b/wger/weight/tests/test_entry.pyindex 0ac25ce35..1a66a27ef 100644--- a/wger/weight/tests/test_entry.py+++ b/wger/weight/tests/test_entry.py@@ -27,21 +27,6 @@ from wger.measurements.models import (Measurement,)from wger.measurements.models.category import MetricType-from wger.weight.models import WeightEntry---class MealRepresentationTestCase(WgerTestCase):- """- Test the representation of a model- """-- def test_representation(self):- """- Test that the representation of an object is correct- """- self.assertEqual(- str(WeightEntry.objects.get(pk=1)), '2012-10-01 14:30:21.592000+00:00: 77.00 kg'- )class WeightEntryTestCase(api_base_test.ApiBaseResourceTestCase):