Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· openaiHugging Face Suzhen/CodeChat

def create(self, validateddata): author = self.context.get("request").user tags =…

  1. 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

  2. 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, поэтому вам может потребоваться обновить связи связанных моделей вручную, если они есть.

  3. 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.data
    

    class Meta: model = Recipe exclude = ("pub_date",)

    используй bulkcreate

  4. 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",)
    
  5. 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'

  6. 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.

    Пожалуйста, попробуйте использовать этот код и проверить, исправляет ли он ошибку.