Skip to main content
 首页 » 编程设计

python之多对多的嵌套序列化器

2024年09月07日12jillzhang

我是 Python 和 Django 的新手。我正在使用 Django-Rest-Framework 创建 api 我想序列化可以接受以下格式的 json 的数据:

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

但是我可以使用以下格式将数据保存在数据库中:

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

我不确定如何将字典转换为集合字段。我知道 List field和 list serialiser但不确定如何使用它们。 是否可以使用模型序列化器来做到这一点?

序列化器.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 

模型.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   

请您参考如下方法:

我建议您使用两种不同的序列化器来创建和其他目的。请参阅以下代码段,
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__'