Django Rest Framework:允许在父级或单独创建子模型 [英] Django Rest Framework: Allow child models to be created either within a parent or seperately

查看:107
本文介绍了Django Rest Framework:允许在父级或单独创建子模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一组嵌套的序列化器,例如:

Say I have a set of nested serialisers like:

class ChildSerializer(serializers.ModelSerializer):

    class Meta:
        model = models.Child
        fields = ['id', 'name']


class ParentSerializer(serializers.ModelSerializer):
    children = ChildSerializer(many=True)

    class Meta:
        model = models.Parent
        fields = ['id', 'name', 'children']

    def create(self, validated_data):
        children = validated_data.pop('children')
        parent = super().create(validated_data)
        for child in children: 
            child['parent'] = parent
        self.fields['children'].create(children)
        return parent

如果我将有效载荷发送到 ParentViewSet

If I send the payload to the ParentViewSet:

payload = {
    'name': 'parent',
    'children': [
        {
            'name': 'child',
        }
    ],
}

它可以很好地创建两个模型,但如果我将以下负载发送到 ChildViewSet

It creates both models fine, but if I send the following payload to the ChildViewSet:

payload = {
    'name': 'child',
    'parent': parent.pk,
}

它将失败,因为未包含在 Child 序列化程序中 field 属性。如果包含该属性,则相反。第二个有效负载有效,但是第一个有效负载失败,因为您没有包括 parent 字段(因为您同时创建了两个模型)。

It will fail because it parent isn't included in the Child serializers field attribute. If you include the attribute, the reverse is true. The second payload works, but the first one fails because you aren't including the parent field (since you're creating the two models at the same time).

是否有解决此问题的方法?我想为 Parent Child 创建方法,但是我似乎无法配置序列化程序为此。

Is there a way around this behaviour? I'd like to have create methods for both Parent and Child, but I can't seem to configure my serialisers to do this.

编辑:

models.py

class Parent(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=256)


class Child(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=256)
    parent = models.ForeignKey(Child, on_delete=models.CASCADE, related_name='children')


推荐答案

您可以通过使用另一个序列化程序来实现所需的功能,如JPG在注释中所示。一种方法可能如下:

You can achieve what you want by using another serializer, as JPG sugested in comments. One approach could be the following:

class ChildSerializer(serializers.ModelSerializer):

    class Meta:
        model = models.Child
        fields = ['id', 'name', 'parent']

class ParentChildSerializer(serializers.ModelSerializer):

    class Meta:
        model = models.Child
        fields = ['id', 'name']

class ParentSerializer(serializers.ModelSerializer):
    children = ParentChildSerializer(many=True)

    class Meta:
        model = models.Parent
        fields = ['id', 'name', 'children']

    def create(self, validated_data):
        children = validated_data.pop('children')
        parent = super().create(validated_data)
        for child in children: 
            child['parent'] = parent
        self.fields['children'].create(children)
        return parent

在您的ChildViewSet中,您可以使用ChildSerializer,在您的ParentSerializer中,您可以使用ParentChildSerializer。

Here in your ChildViewSet, you can use ChildSerializer, and in your ParentSerializer, you can use ParentChildSerializer.

这篇关于Django Rest Framework:允许在父级或单独创建子模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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