Nested Serializer for Many to Many

Обновить

April 2019

Просмотры

286 раз

1

Я новичок в Python и Django. Я создаю API с использованием Django-Rest-Framework Я хочу, чтобы данные Serializer, которые могут принимать JSON в формате ниже:

{
"ingredients": ["Sugar","Egg"],
"name": "Cake",
"description": "Dinner Food",
"directions": "direction1"
}

Тем не менее, я могу сохранять данные в БД с ниже формате:

{
"ingredients": [{"name":"Cake"},{"name":"Egg"}],
"name": "Rice",
"description": "Dinner Food",
"directions": "direction1"
}

Я не знаю , как я могу конвертировать словарь в множеству поле. Я отдаю себе отчет в поле Списка и список serialiser , но не знает , как использовать их. Можно ли это сделать с помощью модели serialiser?

Serializer.py

class IngredientSerializer(serializers.ModelSerializer):

    class Meta:
        model = Ingredient
        fields = '__all__'


class RecipeSerializer(serializers.ModelSerializer):
    ingredients = IngredientSerializer(many=True)

        class Meta:
            model = Recipe
            fields = '__all__'

    def create(self, validated_data):
        ingredients_data = validated_data.pop('ingredients')
        print(ingredients_data)
        recipe = Recipe.objects.create(**validated_data)
        for ingredient in ingredients_data:
            ingredient, created = Ingredient.objects.get_or_create(name=ingredient['name'])
            recipe.ingredients.add(ingredient)
        return recipe

Model.py

class Ingredient(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name


class Recipe(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField(blank=True, null=True)
    directions = models.TextField()
    ingredients = models.ManyToManyField(Ingredient)

    def __str__(self):
        return self.name

view.py

class RecipieView(viewsets.ModelViewSet):
    queryset = Recipe.objects.all()
    serializer_class = RecipeSerializer


class IngredientView(viewsets.ModelViewSet):
    queryset = Ingredient.objects.all()
    serializer_class = IngredientSerializer  

1 ответы

0

I would recommend you to use two different serializers for creation purpose and others. See the below snippet,
views.py

class RecipieView(viewsets.ModelViewSet):
    queryset = Recipe.objects.all()
    serializer_class = RecipeMainSerializer

    def get_serializer_class(self):
        if self.action == 'create':
            return RecipeCreateSerializer
        return RecipeMainSerializer


serializer.py

class RecipeCreateSerializer(serializers.ModelSerializer):
    ingredients = serializers.ListField(write_only=True)

    class Meta:
        model = Recipe
        fields = '__all__'

    def create(self, validated_data):
        ingredients_data = validated_data.pop('ingredients')
        recipe = Recipe.objects.create(**validated_data)
        for ingredient in ingredients_data:
            ingredient, created = Ingredient.objects.get_or_create(name=ingredient)
            recipe.ingredients.add(ingredient)
        return recipe


class RecipeMainSerializer(serializers.ModelSerializer):
    ingredients = IngredientSerializer(many=True)

    class Meta:
        model = Recipe
        fields = '__all__'
JPG