Skip to content

Commit e604850

Browse files
committed
fix: ingredients mess on recipe editing
1 parent 89cb62c commit e604850

File tree

2 files changed

+27
-22
lines changed

2 files changed

+27
-22
lines changed

backend/foodgram/foodapp/serializers.py

Lines changed: 27 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -269,20 +269,34 @@ def create(self, validated_data):
269269
def update(self, instance, validated_data):
270270
if 'tags' not in validated_data:
271271
raise serializers.ValidationError({'tags': 'Обязательное поле.'})
272-
else:
273-
instance.tags.set(validated_data.pop('tags'))
274272
if 'recipe_ingredients' not in validated_data:
275-
raise serializers.ValidationError({'tags': 'Обязательное поле.'})
276-
else:
277-
ingredients = validated_data.pop('recipe_ingredients')
278-
instance.recipe_ingredients.all().delete()
279-
for ingredient in ingredients:
280-
ingredient_instance = Ingredient.objects.get(
281-
id=ingredient['id'])
282-
RecipeIngredient.objects.create(recipe=instance,
283-
ingredient=ingredient_instance,
284-
amount=ingredient['amount'])
285-
return super().update(instance, validated_data)
273+
raise serializers.ValidationError({'ingredients': 'Обязательное поле.'})
274+
275+
# Обновляем базовые поля
276+
instance.name = validated_data.get('name', instance.name)
277+
instance.image = validated_data.get('image', instance.image)
278+
instance.text = validated_data.get('text', instance.text)
279+
instance.cooking_time = validated_data.get('cooking_time', instance.cooking_time)
280+
281+
# Обновляем теги
282+
instance.tags.clear() # Сначала очищаем
283+
instance.tags.set(validated_data.pop('tags')) # Потом устанавливаем новые
284+
285+
# Обновляем ингредиенты
286+
ingredients_data = validated_data.pop('recipe_ingredients')
287+
instance.recipe_ingredients.all().delete() # Удаляем старые ингредиенты
288+
289+
# Создаем новые ингредиенты
290+
RecipeIngredient.objects.bulk_create([
291+
RecipeIngredient(
292+
recipe=instance,
293+
ingredient_id=ingredient_data['id'],
294+
amount=ingredient_data['amount']
295+
) for ingredient_data in ingredients_data
296+
])
297+
298+
instance.save()
299+
return instance
286300

287301

288302
class RecipeShortSerializer(serializers.ModelSerializer):

backend/foodgram/foodgram/asgi.py

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,3 @@
1-
"""
2-
ASGI config for foodgram project.
3-
4-
It exposes the ASGI callable as a module-level variable named ``application``.
5-
6-
For more information on this file, see
7-
https://docs.djangoproject.com/en/4.2/howto/deployment/asgi/
8-
"""
9-
101
import os
112

123
from django.core.asgi import get_asgi_application

0 commit comments

Comments
 (0)