Files
Django_TasksApp/main/food/migrations/0009_backfill_food_hydration.py
T
2026-10-11 20:46:55 +02:00

35 lines
1.4 KiB
Python

import re
from decimal import Decimal
from django.db import migrations
PATTERNS = (
('water', r'water'), ('juice', r'juice|sap|limonade|lemonade'),
('milk', r'milk|melk|chocolademelk'),
('coffee', r'coffee|koffie|espresso|cappuccino|latte'),
('tea', r'tea|thee'), ('smoothie', r'smoothie|shake'),
('other_drink', r'soda|cola|drink|drank|bier|beer|wine|wijn'),
)
def backfill_food_drinks(apps, schema_editor):
Entry = apps.get_model('food', 'FoodLogEntry')
for entry in Entry.objects.filter(unit='ml', hydration_source='').iterator():
name = entry.product_name_snapshot.casefold()
kind = next((kind for kind, words in PATTERNS
if re.search(rf'(?<!\w)(?:{words})(?!\w)', name)), '')
if not kind:
Entry.objects.filter(pk=entry.pk).update(hydration_source='inferred')
continue
amount = Decimal(entry.amount)
Entry.objects.filter(pk=entry.pk).update(beverage_volume_ml=amount,
hydration_amount_ml=amount, hydration_factor_snapshot=Decimal('1'),
hydration_kind=kind, hydration_source='inferred')
Entry.objects.filter(hydration_source='').update(hydration_source='inferred')
class Migration(migrations.Migration):
dependencies = [('food', '0008_food_hydration'), ('planner', '0021_automatic_hydration')]
operations = [migrations.RunPython(backfill_food_drinks, migrations.RunPython.noop)]