小编典典

Django Rest Framework可写嵌套序列化器

django

我正在编写一个食谱管理器作为课程的示例项目。除了使用一些非常基本的功能之外,我对DRF并没有太多的经验。目的是:

创建具有相关成分的新配方。在创建配方对象的同时创建成分对象。

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

这样可以在数据库中成功创建配方对象和配料对象,但不会将配料列表与配方相关联。我认为这是因为运行时ingredients_data = validated_data.pop('ingredients'),validated_data字典中的成分被删除了,所以当我使用创建新的配方时validated_data,没有相关的成分。

但是,我似乎无法找出一种使配料与配方相关联的方法。


阅读 704

收藏
2020-03-29

共1个答案

小编典典

我发现在创建所有未创建的对象之前,无法建立ManyToMany关系。(有关多对多关系,请参见Django Docs 页面。)

这是工作代码:

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

以下是我的update()代码。但是,我已经好几年没有对此进行研究了,也不知道它是正确的还是良好的。我已经有一段时间没有在Python或Django上工作了,所以请一take而就:

def update(self, instance, validated_data):
    ingredients_data = validated_data.pop('ingredients')

    instance.name = validated_data.get('name', instance.name)
    instance.description = validated_data.get('description', instance.description)
    instance.directions = validated_data.get('directions', instance.directions)
    instance.photo = validated_data.get('photo', instance.photo)

    ingredients_list = []

    for ingredient in ingredients_data:
        ingredient, created = Ingredient.objects.get_or_create(name=ingredient["name"])
        ingredients_list.append(ingredient)

    instance.ingredients = ingredients_list
    instance.save()
    return instance
2020-03-29