Форум сайта python.su
Привет, в общем на Джанго проект, надо по АПИ передать POST запрос на добавлении нового рецепта. Да-да рецепта
В целом есть model.Recipe, с атрибутом ingredients
ingredients = models.ManyToManyField(Ingredient, through='IngredientInRecipe')
recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) ingredient = models.ForeignKey(Ingredient, on_delete=models.SET_NULL, null=True) amount = models.DecimalField(max_digits=6, decimal_places=1, validators=[MinValueValidator(1)] )
ingredients = IngredientInRecipeSerializer(many=True)
class IngredientInRecipeSerializer(serializers.ModelSerializer): """Serializer for ingredient in recipe objects""" ingredient = serializers.PrimaryKeyRelatedField( queryset=Ingredient.objects.all() ) amount = serializers.DecimalField(max_digits=6, decimal_places=1) def create(self, validated_data): ingredient = validated_data.pop('ingredient') amount = validated_data.pop('amount') ingredient_in_recipe = IngredientInRecipe.objects.create(ingredient=ingredient, amount=amount) return ingredient_in_recipe
"ingredients": [
{
"id": 1,
"amount": 10
},
{
"id": 2,
"amount": 20
}
],
{
"ingredients": [
{
"ingredient": [
"This field is required."
]
},
{
"ingredient": [
"This field is required."
]
}
]
}
Офлайн