我是Python和Django的新手。我正在使用Django-Rest-Framework创建api我想序列化可以接受以下格式的json的数据:
{
"ingredients": ["Sugar","Egg"],
"name": "Cake",
"description": "Dinner Food",
"directions": "direction1"
}
但是我可以使用以下格式在db中保存数据:
{
"ingredients": [{"name":"Cake"},{"name":"Egg"}],
"name": "Rice",
"description": "Dinner Food",
"directions": "direction1"
}
我不知道如何将字典转换为设置字段。我知道List field和list 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
答案 0 :(得分:0)
我建议您使用两种不同的序列化程序用于创建目的和其他目的。请参阅以下代码段,
的 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__'