Django Rest框架可写嵌套序列化程序 [英] Django Rest Framework writable nested serializers

查看:99
本文介绍了Django Rest框架可写嵌套序列化程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个食谱组织者作为课程的示例项目。除了使用一些非常基本的功能之外,我对DRF的经验也不是很高。这是目标:



创建一个新的配方与相关的成分。在创建配方对象的同时创建成分对象。



models.py:

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

def __str __(self)
return self.name


class食谱(models.Model):
name = models.CharField(max_length = 100)
description = models。 TextField(blank = True,null = True,help_text =这是您的食谱的快速描述)
directions = models.TextField(help_text =如何制作食谱)
ingredients = models .ManyToManyField(Ingredient)

def __str __(self):
return self.name



serializers.py

  class IngredientSerializer serializer.ModelSerializer):

class Meta:
model = Ingredient


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

class Meta:
model =配方

def create(self,validated_data):
ingredients_data = validated_data。 pop('ingredients')
recipe = Recipe.objects.create(** validated_data)
在ingredients_data中的ingredients_data:
Ingredient.objects.create(** ingredients_data)
返回食谱

这成功地在数据库中创建了食谱对象和成分对象,但不将食谱配料清单。我假设这是因为当我运行 ingredients_data = validated_data.pop('ingredients')时, validated_data 删除原料,所以当我使用 validated_data 创建新的食谱时,没有相关的成分。



然而我似乎没有找出一种方法来保持与食谱相关的成分。

解决方案

我想到,ManyToMany关系可以'直到所有未处理的对象都被创建为止。 (有关许多文档,请参阅Django文档页面对于许多关系



以下是工作代码:



序列化器。

$ b

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

class Meta:
model = Recipe

def create(self,validated_data):
ingredients_data = validated_data.pop('ingredients')
recipe = Recipe.objects.create(** validated_data)

在ingredients_data中的成分:
ingredients,created = Ingredient.objects.get_or_create(name = ingredients ['name'])
recipe.ingredients.add(成分)
返回食谱


I'm writing a recipe organizer as a sample project for a class. I'm not very experienced with DRF other than using some very basic functionality. Here's the objective:

Create a new Recipe with associated Ingredients. Create the Ingredient objects at the same time as creating the Recipe object.

models.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, help_text="This is a quick description of your recipe")
    directions = models.TextField(help_text="How to make the recipe")
    ingredients = models.ManyToManyField(Ingredient)

    def __str__(self):
        return self.name


serializers.py

class IngredientSerializer(serializers.ModelSerializer):

    class Meta:
        model = Ingredient


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

    class Meta:
        model = Recipe

    def create(self, validated_data):
        ingredients_data = validated_data.pop('ingredients')
        recipe = Recipe.objects.create(**validated_data)
        for ingredient_data in ingredients_data:
            Ingredient.objects.create(**ingredient_data)
        return recipe

This successfully creates the Recipe object AND the Ingredients objects in the database, but doesn't associate the list of Ingredients with the Recipe. I assume this is because when I run ingredients_data = validated_data.pop('ingredients'), the validated_data dictionary gets its Ingredients removed, so when I create a new Recipe using validated_data, there aren't associated ingredients.

However I can't seem to figure out a way to keep ingredients associated with the recipe.

解决方案

I figured out that ManyToMany relationships can't be established until all of the uncreated objects have been created. (See the Django Docs page on many-to-many relationships.)

Here's the working code:

serializers.py

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

    class Meta:
        model = Recipe

    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['name'])
            recipe.ingredients.add(ingredient)
        return recipe

这篇关于Django Rest框架可写嵌套序列化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆