26 lines
851 B
Python
26 lines
851 B
Python
from decimal import Decimal
|
|
|
|
|
|
NUTRIENTS = (
|
|
('energy_kcal_100', 'calories_kcal'),
|
|
('carbohydrates_100', 'carbohydrates_g'),
|
|
('protein_100', 'protein_g'),
|
|
('fat_100', 'fat_g'),
|
|
('fibre_100', 'fibre_g'),
|
|
('sugars_100', 'sugars_g'),
|
|
('salt_100', 'salt_g'),
|
|
)
|
|
|
|
|
|
def apply_product_snapshot(entry, product):
|
|
"""Apply the same product snapshot and nutrition calculation for web and API logs."""
|
|
entry.product = product
|
|
entry.product_name_snapshot = product.product_name
|
|
entry.brand_snapshot = product.brand
|
|
entry.barcode_snapshot = product.barcode
|
|
entry.source = product.source
|
|
factor = entry.amount / Decimal('100')
|
|
for source, target in NUTRIENTS:
|
|
value = getattr(product, source)
|
|
setattr(entry, target, (value * factor).quantize(Decimal('0.001')) if value is not None else None)
|