|
3 | 3 |
|
4 | 4 | from django.contrib.auth import get_user_model |
5 | 5 | from django.core.files.base import ContentFile |
| 6 | +from django.shortcuts import get_object_or_404 |
6 | 7 | from rest_framework import serializers |
7 | 8 |
|
8 | 9 | from .constants import (DEFAULT_RECIPES_AMOUNT_AT_SUBSCRIPTIONS_PAGE, |
@@ -267,22 +268,40 @@ def create(self, validated_data): |
267 | 268 | return recipe |
268 | 269 |
|
269 | 270 | def update(self, instance, validated_data): |
| 271 | + print("Входящие данные: ", validated_data) |
| 272 | + print("Ингредиенты: ", validated_data.get('recipe_ingredients')) |
270 | 273 | if 'tags' not in validated_data: |
271 | 274 | raise serializers.ValidationError({'tags': 'Обязательное поле.'}) |
272 | | - else: |
273 | | - instance.tags.set(validated_data.pop('tags')) |
274 | 275 | 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) |
| 276 | + raise serializers.ValidationError( |
| 277 | + {'ingredients': 'Обязательное поле.'}) |
| 278 | + instance.name = validated_data.get('name', instance.name) |
| 279 | + instance.image = validated_data.get('image', instance.image) |
| 280 | + instance.text = validated_data.get('text', instance.text) |
| 281 | + instance.cooking_time = validated_data.get('cooking_time', |
| 282 | + instance.cooking_time) |
| 283 | + instance.tags.clear() |
| 284 | + instance.tags.set(validated_data.pop('tags')) |
| 285 | + recipe_ingredients = validated_data.pop('recipe_ingredients') |
| 286 | + instance.recipe_ingredients.all().delete() |
| 287 | + # RecipeIngredient.objects.bulk_create([ |
| 288 | + # RecipeIngredient( |
| 289 | + # recipe=instance, |
| 290 | + # ingredient=get_object_or_404(Ingredient, |
| 291 | + # id=ingredient['id']), |
| 292 | + # amount=ingredient['amount'] |
| 293 | + # ) for ingredient in recipe_ingredients]) |
| 294 | + for ingredient in recipe_ingredients: |
| 295 | + print(f"Создаю связь: Рецепт={instance.name}, " |
| 296 | + f"Ингредиент={ingredient.name}, " |
| 297 | + f"Количество={ingredient['amount']}") |
| 298 | + |
| 299 | + RecipeIngredient.objects.create( |
| 300 | + recipe=instance, |
| 301 | + ingredient=get_object_or_404(Ingredient, id=ingredient['id']), |
| 302 | + amount=ingredient['amount']) |
| 303 | + instance.save() |
| 304 | + return instance |
286 | 305 |
|
287 | 306 |
|
288 | 307 | class RecipeShortSerializer(serializers.ModelSerializer): |
|
0 commit comments