Self hosted FLOSS fitness/workout, nutrition and weight tracker
Prevent duplicates of ingredient weight units on OFF import
Roland Geiderbcfdde1a966d
diff --git a/wger/nutrition/models/ingredient.py b/wger/nutrition/models/ingredient.pyindex 578912841..ee7dd6fee 100644--- a/wger/nutrition/models/ingredient.py+++ b/wger/nutrition/models/ingredient.py@@ -484,14 +484,19 @@ class Ingredient(AbstractLicenseModel, models.Model):else:name = unit- existing_weight_unit = IngredientWeightUnit.objects.filter(- ingredient=self,- name__iexact=name,- ).first()+ # Try to find the unit locally. This can happen either because the name matches or+ # the exact gram amount. This would cover scenarios where the name was changed on+ # OFF's side or our serving size parser, e.g.: "2 biscuits" -> "1 Portion (2 biscuits)"+ existing_weight_unit = (+ IngredientWeightUnit.objects.filter(ingredient=self)+ .filter(models.Q(name__iexact=name) | models.Q(gram=gram))+ .first()+ )if existing_weight_unit:+ existing_weight_unit.name = nameexisting_weight_unit.gram = gram- existing_weight_unit.save(update_fields=['gram'])+ existing_weight_unit.save(update_fields=['name', 'gram'])return False, True # (created, updated)else:IngredientWeightUnit.objects.create(diff --git a/wger/nutrition/tests/test_ingredient.py b/wger/nutrition/tests/test_ingredient.pyindex 957591183..985e34540 100644--- a/wger/nutrition/tests/test_ingredient.py+++ b/wger/nutrition/tests/test_ingredient.py@@ -529,6 +529,26 @@ class IngredientModelTestCase(WgerTestCase):)self.assertEqual(ingredient_unit.gram, 25)+ @patch('openfoodfacts.api.ProductResource.get')+ def test_reimport_same_gram_different_name_does_not_duplicate(self, mock_api: MagicMock):+ """+ When OFF changes the serving_size text but the gram value stays,+ the existing unit is reused (matched by gram) instead of creating a duplicate.+ """+ self.off_response['serving_size'] = '2 biscuits (30 g)'+ mock_api.return_value = self.off_response+ ingredient = Ingredient.fetch_ingredient_from_off('1234')++ self.off_response['serving_size'] = '3 biscuits (30 g)'+ ingredient.update_or_create_serving_unit_from_off(+ extract_info_from_off(self.off_response, ingredient.language_id)+ )++ units = IngredientWeightUnit.objects.filter(ingredient=ingredient)+ self.assertEqual(units.count(), 1)+ self.assertEqual(units.first().name, '1 Portion (3 biscuits)')+ self.assertEqual(units.first().gram, 30)+@patch('openfoodfacts.api.ProductResource.get')def test_fetch_from_off_success_long_name(self, mock_api: MagicMock):"""