adding food logging, phase 1
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
from django.contrib import admin
|
||||
|
||||
from .models import FoodFavourite, FoodLogEntry, FoodPortion, FoodProduct
|
||||
|
||||
|
||||
@admin.register(FoodProduct)
|
||||
class FoodProductAdmin(admin.ModelAdmin):
|
||||
list_display = ('product_name', 'brand', 'barcode', 'source', 'owner', 'fetched_at')
|
||||
list_filter = ('source', 'fetched_at')
|
||||
search_fields = ('product_name', 'brand', 'barcode')
|
||||
|
||||
|
||||
@admin.register(FoodLogEntry)
|
||||
class FoodLogEntryAdmin(admin.ModelAdmin):
|
||||
list_display = ('date', 'user', 'meal', 'product_name_snapshot', 'amount', 'unit', 'calories_kcal')
|
||||
list_filter = ('date', 'meal', 'user')
|
||||
search_fields = ('product_name_snapshot', 'brand_snapshot', 'barcode_snapshot')
|
||||
|
||||
|
||||
@admin.register(FoodFavourite)
|
||||
class FoodFavouriteAdmin(admin.ModelAdmin):
|
||||
list_display = ('user', 'product', 'created_at')
|
||||
|
||||
|
||||
@admin.register(FoodPortion)
|
||||
class FoodPortionAdmin(admin.ModelAdmin):
|
||||
list_display = ('user', 'product', 'label', 'amount', 'unit', 'is_default')
|
||||
@@ -0,0 +1,20 @@
|
||||
from django import forms
|
||||
|
||||
from .models import FoodProduct, Unit
|
||||
|
||||
|
||||
class ManualFoodForm(forms.ModelForm):
|
||||
class Meta:
|
||||
model = FoodProduct
|
||||
fields = ('product_name', 'brand', 'base_unit', 'energy_kcal_100', 'carbohydrates_100', 'protein_100', 'fat_100', 'fibre_100', 'sugars_100', 'salt_100')
|
||||
labels = {
|
||||
'energy_kcal_100': 'Calories per 100 g or ml',
|
||||
'carbohydrates_100': 'Carbohydrates per 100 g or ml',
|
||||
'protein_100': 'Protein per 100 g or ml',
|
||||
'fat_100': 'Fat per 100 g or ml',
|
||||
}
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
for field in ('energy_kcal_100', 'carbohydrates_100', 'protein_100', 'fat_100'):
|
||||
self.fields[field].required = True
|
||||
@@ -0,0 +1,112 @@
|
||||
# Generated by Django 6.1.1 on 2026-10-03 18:39
|
||||
|
||||
import django.core.validators
|
||||
import django.db.models.deletion
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='FoodProduct',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('barcode', models.CharField(blank=True, db_index=True, max_length=64)),
|
||||
('product_name', models.CharField(max_length=255)),
|
||||
('brand', models.CharField(blank=True, max_length=255)),
|
||||
('image_url', models.URLField(blank=True)),
|
||||
('package_quantity', models.CharField(blank=True, max_length=100)),
|
||||
('serving_size_text', models.CharField(blank=True, max_length=100)),
|
||||
('serving_amount', models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(0.001)])),
|
||||
('serving_unit', models.CharField(blank=True, choices=[('g', 'g'), ('ml', 'ml')], max_length=2)),
|
||||
('base_unit', models.CharField(choices=[('g', 'g'), ('ml', 'ml')], default='g', max_length=2)),
|
||||
('energy_kcal_100', models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(0)])),
|
||||
('carbohydrates_100', models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(0)])),
|
||||
('protein_100', models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(0)])),
|
||||
('fat_100', models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(0)])),
|
||||
('saturated_fat_100', models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(0)])),
|
||||
('sugars_100', models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(0)])),
|
||||
('fibre_100', models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(0)])),
|
||||
('salt_100', models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(0)])),
|
||||
('source', models.CharField(choices=[('openfoodfacts', 'Open Food Facts'), ('manual', 'Manual')], default='manual', max_length=16)),
|
||||
('raw_data', models.JSONField(blank=True, default=dict)),
|
||||
('fetched_at', models.DateTimeField(blank=True, null=True)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('updated_at', models.DateTimeField(auto_now=True)),
|
||||
('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='food_products', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='FoodPortion',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('label', models.CharField(max_length=100)),
|
||||
('amount', models.DecimalField(decimal_places=3, max_digits=10, validators=[django.core.validators.MinValueValidator(0.001)])),
|
||||
('unit', models.CharField(choices=[('g', 'g'), ('ml', 'ml')], max_length=2)),
|
||||
('is_default', models.BooleanField(default=False)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('updated_at', models.DateTimeField(auto_now=True)),
|
||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='food_portions', to=settings.AUTH_USER_MODEL)),
|
||||
('product', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='portions', to='food.foodproduct')),
|
||||
],
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='FoodLogEntry',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('date', models.DateField(db_index=True)),
|
||||
('time', models.TimeField(blank=True, null=True)),
|
||||
('meal', models.CharField(choices=[('breakfast', 'Breakfast'), ('lunch', 'Lunch'), ('dinner', 'Dinner'), ('snacks', 'Snacks')], max_length=9)),
|
||||
('product_name_snapshot', models.CharField(max_length=255)),
|
||||
('brand_snapshot', models.CharField(blank=True, max_length=255)),
|
||||
('barcode_snapshot', models.CharField(blank=True, max_length=64)),
|
||||
('portion_label_snapshot', models.CharField(blank=True, max_length=100)),
|
||||
('amount', models.DecimalField(decimal_places=3, max_digits=10, validators=[django.core.validators.MinValueValidator(0.001)])),
|
||||
('unit', models.CharField(choices=[('g', 'g'), ('ml', 'ml')], max_length=2)),
|
||||
('calories_kcal', models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(0)])),
|
||||
('carbohydrates_g', models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(0)])),
|
||||
('protein_g', models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(0)])),
|
||||
('fat_g', models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(0)])),
|
||||
('fibre_g', models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(0)])),
|
||||
('sugars_g', models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(0)])),
|
||||
('salt_g', models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(0)])),
|
||||
('source', models.CharField(choices=[('openfoodfacts', 'Open Food Facts'), ('manual', 'Manual')], default='manual', max_length=16)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('updated_at', models.DateTimeField(auto_now=True)),
|
||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='food_log_entries', to=settings.AUTH_USER_MODEL)),
|
||||
('product', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='log_entries', to='food.foodproduct')),
|
||||
],
|
||||
options={
|
||||
'ordering': ('date', 'time', 'pk'),
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='FoodFavourite',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='food_favourites', to=settings.AUTH_USER_MODEL)),
|
||||
('product', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='favourites', to='food.foodproduct')),
|
||||
],
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name='foodproduct',
|
||||
constraint=models.UniqueConstraint(condition=models.Q(('barcode', ''), _negated=True), fields=('owner', 'barcode'), name='food_unique_owner_barcode'),
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name='foodportion',
|
||||
constraint=models.UniqueConstraint(fields=('user', 'product', 'label'), name='food_unique_portion_label'),
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name='foodfavourite',
|
||||
constraint=models.UniqueConstraint(fields=('user', 'product'), name='food_unique_favourite'),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,125 @@
|
||||
from django.conf import settings
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.core.validators import MinValueValidator
|
||||
from django.db import models
|
||||
from django.db.models import Q
|
||||
|
||||
|
||||
NON_NEGATIVE = [MinValueValidator(0)]
|
||||
POSITIVE = [MinValueValidator(0.001)]
|
||||
|
||||
|
||||
class Unit(models.TextChoices):
|
||||
GRAM = 'g', 'g'
|
||||
MILLILITRE = 'ml', 'ml'
|
||||
|
||||
|
||||
class MealType(models.TextChoices):
|
||||
BREAKFAST = 'breakfast', 'Breakfast'
|
||||
LUNCH = 'lunch', 'Lunch'
|
||||
DINNER = 'dinner', 'Dinner'
|
||||
SNACKS = 'snacks', 'Snacks'
|
||||
|
||||
|
||||
class FoodProduct(models.Model):
|
||||
class Source(models.TextChoices):
|
||||
OPEN_FOOD_FACTS = 'openfoodfacts', 'Open Food Facts'
|
||||
MANUAL = 'manual', 'Manual'
|
||||
|
||||
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='food_products')
|
||||
barcode = models.CharField(max_length=64, blank=True, db_index=True)
|
||||
product_name = models.CharField(max_length=255)
|
||||
brand = models.CharField(max_length=255, blank=True)
|
||||
image_url = models.URLField(blank=True)
|
||||
package_quantity = models.CharField(max_length=100, blank=True)
|
||||
serving_size_text = models.CharField(max_length=100, blank=True)
|
||||
serving_amount = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=POSITIVE)
|
||||
serving_unit = models.CharField(max_length=2, choices=Unit.choices, blank=True)
|
||||
base_unit = models.CharField(max_length=2, choices=Unit.choices, default=Unit.GRAM)
|
||||
energy_kcal_100 = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE)
|
||||
carbohydrates_100 = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE)
|
||||
protein_100 = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE)
|
||||
fat_100 = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE)
|
||||
saturated_fat_100 = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE)
|
||||
sugars_100 = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE)
|
||||
fibre_100 = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE)
|
||||
salt_100 = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE)
|
||||
source = models.CharField(max_length=16, choices=Source.choices, default=Source.MANUAL)
|
||||
raw_data = models.JSONField(default=dict, blank=True)
|
||||
fetched_at = models.DateTimeField(null=True, blank=True)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
class Meta:
|
||||
constraints = [models.UniqueConstraint(fields=('owner', 'barcode'), condition=~Q(barcode=''), name='food_unique_owner_barcode')]
|
||||
|
||||
def __str__(self):
|
||||
return self.product_name
|
||||
|
||||
|
||||
class FoodLogEntry(models.Model):
|
||||
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='food_log_entries')
|
||||
date = models.DateField(db_index=True)
|
||||
time = models.TimeField(null=True, blank=True)
|
||||
meal = models.CharField(max_length=9, choices=MealType.choices)
|
||||
product = models.ForeignKey(FoodProduct, on_delete=models.SET_NULL, null=True, blank=True, related_name='log_entries')
|
||||
product_name_snapshot = models.CharField(max_length=255)
|
||||
brand_snapshot = models.CharField(max_length=255, blank=True)
|
||||
barcode_snapshot = models.CharField(max_length=64, blank=True)
|
||||
portion_label_snapshot = models.CharField(max_length=100, blank=True)
|
||||
amount = models.DecimalField(max_digits=10, decimal_places=3, validators=POSITIVE)
|
||||
unit = models.CharField(max_length=2, choices=Unit.choices)
|
||||
calories_kcal = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE)
|
||||
carbohydrates_g = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE)
|
||||
protein_g = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE)
|
||||
fat_g = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE)
|
||||
fibre_g = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE)
|
||||
sugars_g = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE)
|
||||
salt_g = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE)
|
||||
source = models.CharField(max_length=16, choices=FoodProduct.Source.choices, default=FoodProduct.Source.MANUAL)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
class Meta:
|
||||
ordering = ('date', 'time', 'pk')
|
||||
|
||||
def clean(self):
|
||||
super().clean()
|
||||
if self.product_id and self.user_id and self.product.owner_id != self.user_id:
|
||||
raise ValidationError({'product': 'Choose one of your own food products.'})
|
||||
|
||||
def __str__(self):
|
||||
return f'{self.product_name_snapshot} on {self.date}'
|
||||
|
||||
|
||||
class FoodFavourite(models.Model):
|
||||
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='food_favourites')
|
||||
product = models.ForeignKey(FoodProduct, on_delete=models.CASCADE, related_name='favourites')
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
class Meta:
|
||||
constraints = [models.UniqueConstraint(fields=('user', 'product'), name='food_unique_favourite')]
|
||||
|
||||
def clean(self):
|
||||
super().clean()
|
||||
if self.product_id and self.user_id and self.product.owner_id != self.user_id:
|
||||
raise ValidationError({'product': 'Choose one of your own food products.'})
|
||||
|
||||
|
||||
class FoodPortion(models.Model):
|
||||
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='food_portions')
|
||||
product = models.ForeignKey(FoodProduct, on_delete=models.CASCADE, related_name='portions')
|
||||
label = models.CharField(max_length=100)
|
||||
amount = models.DecimalField(max_digits=10, decimal_places=3, validators=POSITIVE)
|
||||
unit = models.CharField(max_length=2, choices=Unit.choices)
|
||||
is_default = models.BooleanField(default=False)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
class Meta:
|
||||
constraints = [models.UniqueConstraint(fields=('user', 'product', 'label'), name='food_unique_portion_label')]
|
||||
|
||||
def clean(self):
|
||||
super().clean()
|
||||
if self.product_id and self.user_id and self.product.owner_id != self.user_id:
|
||||
raise ValidationError({'product': 'Choose one of your own food products.'})
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.db import IntegrityError, transaction
|
||||
from django.test import TestCase
|
||||
from django.urls import reverse
|
||||
|
||||
from .models import FoodFavourite, FoodLogEntry, FoodPortion, FoodProduct, MealType, Unit
|
||||
|
||||
|
||||
class FoodFoundationTests(TestCase):
|
||||
def setUp(self):
|
||||
self.user = get_user_model().objects.create_user(username='food-one', password='test-password')
|
||||
self.other = get_user_model().objects.create_user(username='food-two', password='test-password')
|
||||
self.product = FoodProduct.objects.create(owner=self.user, product_name='Yoghurt', barcode='123', base_unit=Unit.GRAM)
|
||||
|
||||
def test_meals_are_fixed(self):
|
||||
self.assertEqual(list(MealType.values), ['breakfast', 'lunch', 'dinner', 'snacks'])
|
||||
|
||||
def test_missing_nutrients_remain_null(self):
|
||||
self.product.refresh_from_db()
|
||||
self.assertIsNone(self.product.energy_kcal_100)
|
||||
self.assertIsNone(self.product.protein_100)
|
||||
|
||||
def test_favourite_and_portion_uniqueness(self):
|
||||
FoodFavourite.objects.create(user=self.user, product=self.product)
|
||||
FoodPortion.objects.create(user=self.user, product=self.product, label='My bowl', amount=Decimal('300'), unit=Unit.GRAM)
|
||||
with self.assertRaises(IntegrityError), transaction.atomic():
|
||||
FoodFavourite.objects.create(user=self.user, product=self.product)
|
||||
with self.assertRaises(IntegrityError), transaction.atomic():
|
||||
FoodPortion.objects.create(user=self.user, product=self.product, label='My bowl', amount=Decimal('200'), unit=Unit.GRAM)
|
||||
|
||||
def test_log_snapshot_survives_product_edit(self):
|
||||
entry = FoodLogEntry.objects.create(user=self.user, date=date(2026, 10, 3), meal=MealType.BREAKFAST,
|
||||
product=self.product, product_name_snapshot='Yoghurt', amount=Decimal('300'), unit=Unit.GRAM,
|
||||
calories_kcal=Decimal('174'))
|
||||
self.product.product_name = 'Renamed yoghurt'
|
||||
self.product.energy_kcal_100 = Decimal('100')
|
||||
self.product.save()
|
||||
entry.refresh_from_db()
|
||||
self.assertEqual(entry.product_name_snapshot, 'Yoghurt')
|
||||
self.assertEqual(entry.calories_kcal, Decimal('174'))
|
||||
|
||||
def test_cross_user_product_reference_rejected(self):
|
||||
for item in (
|
||||
FoodFavourite(user=self.other, product=self.product),
|
||||
FoodPortion(user=self.other, product=self.product, label='Bowl', amount=Decimal('100'), unit=Unit.GRAM),
|
||||
FoodLogEntry(user=self.other, product=self.product, date=date(2026, 10, 3), meal=MealType.LUNCH,
|
||||
product_name_snapshot='Yoghurt', amount=Decimal('100'), unit=Unit.GRAM),
|
||||
):
|
||||
with self.assertRaises(ValidationError):
|
||||
item.full_clean()
|
||||
|
||||
def test_food_route_requires_login(self):
|
||||
self.assertEqual(self.client.get(reverse('food:diary')).status_code, 302)
|
||||
self.client.force_login(self.user)
|
||||
self.assertEqual(self.client.get(reverse('food:diary')).status_code, 200)
|
||||
|
||||
def test_food_goals_reject_negative_values(self):
|
||||
from planner.forms import FoodGoalForm
|
||||
|
||||
form = FoodGoalForm(data={'daily_calorie_goal': '-1', 'carbohydrate_goal_g': '-1',
|
||||
'protein_goal_g': '10', 'fat_goal_g': '0'})
|
||||
self.assertFalse(form.is_valid())
|
||||
Reference in New Issue
Block a user