def create(self, validateddata): author = self.context.get("request").user tags =…
- User
def create(self, validated_data): author = self.context.get("request").user tags = validated_data.pop("tags") ingredients = validated_data.pop("ingredients")
recipe = Recipe.objects.create(author=author, **validated_data) recipe.tags.set(tags) for ingredient in ingredients: amount = ingredient.get("amount") ingredient = get_object_or_404( Ingredient, pk=ingredient.get("id").id ) IngredientInRecipe.objects.create( recipe=recipe, ingredient=ingredient, amount=amount ) return recipe def update(self, instance, validated_data): tags = validated_data.pop("tags", None) if tags is not None: instance.tags.set(tags) ingredients = validated_data.pop("ingredients", None) if ingredients is not None: instance.ingredients.clear() for ingredient in ingredients: amount = ingredient.get("amount") ingredient = get_object_or_404( Ingredient, pk=ingredient.get("id").id ) IngredientInRecipe.objects.update_or_create( recipe=instance, ingredient=ingredient, defaults={"amount": amount}, ) return super().update(instance, validated_data)используй bulkcreate
- Assistant
Использование метода
bulk_createвместоcreateиupdate_or_createможет значительно повысить производительность при работе с большим количеством объектов.Метод
bulk_createпозволяет создавать несколько объектов за один раз, путем передачи списка объектов в качестве параметра. Таким образом, вы можете сократить количество запросов к базе данных и улучшить производительность.В вашем случае, вы можете использовать метод
bulk_createдля создания связейIngredientInRecipeвместо циклаforв функцииcreate. Также, в функцииupdateвы можете использовать методbulk_createдля обновления связейIngredientInRecipeвместоupdate_or_create.Пример использования метода
bulk_create:def create(self, validated_data): author = self.context.get("request").user tags = validated_data.pop("tags") ingredients = validated_data.pop("ingredients") recipe = Recipe.objects.create(author=author, **validated_data) recipe.tags.set(tags) ingredient_in_recipes = [ IngredientInRecipe(recipe=recipe, ingredient=Ingredient.objects.get(id=ingredient["id"]), amount=ingredient["amount"]) for ingredient in ingredients ] IngredientInRecipe.objects.bulk_create(ingredient_in_recipes) return recipe def update(self, instance, validated_data): tags = validated_data.pop("tags", None) if tags is not None: instance.tags.set(tags) ingredients = validated_data.pop("ingredients", None) if ingredients is not None: instance.ingredients.clear() ingredient_in_recipes = [ IngredientInRecipe(recipe=instance, ingredient=Ingredient.objects.get(id=ingredient["id"]), amount=ingredient["amount"]) for ingredient in ingredients ] IngredientInRecipe.objects.bulk_create(ingredient_in_recipes) return super().update(instance, validated_data)Обратите внимание, что при использовании метода
bulk_createне генерируются сигналыpre_saveиpost_save, поэтому вам может потребоваться обновить связи связанных моделей вручную, если они есть. - User
class RecipeCreateUpdateSerializer(serializers.ModelSerializer): author = CustomUserSerializer(read_only=True) tags = serializers.PrimaryKeyRelatedField( queryset=Tag.objects.all(), many=True ) ingredients = CreateUpdateRecipeIngredientsSerializer(many=True) image = Base64ImageField() cooking_time = serializers.IntegerField( validators=[ MinValueValidator( MIN_COOKING_TIME, message=("Время приготовления не может быть меньше" f"{MIN_COOKING_TIME}!") ), MaxValueValidator( MAX_COOKING_TIME, message=("Время приготовления не может быть больше" f"{MAX_COOKING_TIME}!") ) ] )
def validate_tags(self, value): if not value: raise exceptions.ValidationError("Добавьте хотя бы один тег!") return value def validate_ingredients(self, value): if not value: raise exceptions.ValidationError( "Добавьте хотя бы один ингредиент!" ) ingredients = [item["id"] for item in value] for ingredient in ingredients: if ingredients.count(ingredient) > 1: raise exceptions.ValidationError( "Рецепт не может включать два одинаковых ингредиента!" ) return value def create(self, validated_data): author = self.context.get("request").user tags = validated_data.pop("tags") ingredients = validated_data.pop("ingredients") recipe = Recipe.objects.create(author=author, **validated_data) recipe.tags.set(tags) ingredient_in_recipes = [ IngredientInRecipe( recipe=recipe, ingredient=Ingredient.objects.get(id=ingredient["id"]), amount=ingredient["amount"]) for ingredient in ingredients ] IngredientInRecipe.objects.bulk_create(ingredient_in_recipes) return recipe def update(self, instance, validated_data): tags = validated_data.pop("tags", None) if tags is not None: instance.tags.set(tags) ingredients = validated_data.pop("ingredients", None) if ingredients is not None: instance.ingredients.clear() ingredient_in_recipes = [ IngredientInRecipe( recipe=instance, ingredient=Ingredient.objects.get(id=ingredient["id"]), amount=ingredient["amount"]) for ingredient in ingredients ] IngredientInRecipe.objects.bulk_create(ingredient_in_recipes) return super().update(instance, validated_data)def to_representation(self, instance): serializer = RecipeSerializer( instance, context={"request": self.context.get("request")} )
return serializer.dataclass Meta: model = Recipe exclude = ("pub_date",)
используй bulkcreate
- Assistant
class RecipeCreateUpdateSerializer(serializers.ModelSerializer): author = CustomUserSerializer(read_only=True) tags = serializers.PrimaryKeyRelatedField( queryset=Tag.objects.all(), many=True ) ingredients = CreateUpdateRecipeIngredientsSerializer(many=True) image = Base64ImageField() cooking_time = serializers.IntegerField( validators=[ MinValueValidator( MIN_COOKING_TIME, message=("Время приготовления не может быть меньше" f"{MIN_COOKING_TIME}!") ), MaxValueValidator( MAX_COOKING_TIME, message=("Время приготовления не может быть больше" f"{MAX_COOKING_TIME}!") ) ] )
def validate_tags(self, value): if not value: raise exceptions.ValidationError("Добавьте хотя бы один тег!") return value def validate_ingredients(self, value): if not value: raise exceptions.ValidationError( "Добавьте хотя бы один ингредиент!" ) ingredients = [item["id"] for item in value] for ingredient in ingredients: if ingredients.count(ingredient) > 1: raise exceptions.ValidationError( "Рецепт не может включать два одинаковых ингредиента!" ) return value def create(self, validated_data): author = self.context.get("request").user tags = validated_data.pop("tags") ingredients = validated_data.pop("ingredients") recipe = Recipe.objects.create(author=author, **validated_data) recipe.tags.set(tags) ingredient_in_recipes = [ IngredientInRecipe( recipe=recipe, ingredient=Ingredient.objects.get(id=ingredient["id"]), amount=ingredient["amount"]) for ingredient in ingredients ] IngredientInRecipe.objects.bulk_create(ingredient_in_recipes) return recipe def update(self, instance, validated_data): tags = validated_data.pop("tags", None) if tags is not None: instance.tags.set(tags) ingredients = validated_data.pop("ingredients", None) if ingredients is not None: instance.ingredients.clear() ingredient_in_recipes = [ IngredientInRecipe( recipe=instance, ingredient=Ingredient.objects.get(id=ingredient["id"]), amount=ingredient["amount"]) for ingredient in ingredients ] IngredientInRecipe.objects.bulk_create(ingredient_in_recipes) return super().update(instance, validated_data) def to_representation(self, instance): serializer = RecipeSerializer( instance, context={"request": self.context.get("request")} ) return serializer.data class Meta: model = Recipe exclude = ("pub_date",) - User
теперь возникает така ошибка File "/usr/local/lib/python3.7/site-packages/django/db/models/fields/init.py", line 972, in get_prep_value return int(value) TypeError: int() argument must be a string, a bytes-like object or a number, not 'Ingredient'
- Assistant
Ошибка возникает из-за того, что метод
bulk_createожидает объекты, а не их идентификаторы. Вам необходимо передать объектIngredientв качестве значения для поляingredientв объектахIngredientInRecipe.Попробуйте изменить соответствующий код следующим образом:
ingredient_in_recipes = [ IngredientInRecipe( recipe=recipe, ingredient=Ingredient.objects.get(id=ingredient["id"]), amount=ingredient["amount"] ) for ingredient in ingredients ]Здесь мы получаем объект
Ingredientс использованием идентификатораingredient["id"]и передаем его в качестве значения для поляingredient.Пожалуйста, попробуйте использовать этот код и проверить, исправляет ли он ошибку.