简体   繁体   English

Django Rest Framework的双重嵌套序列化器

[英]Double-nested serializers with Django Rest Framework

Is this possible with DRF using ModelSerializers? 使用ModelSerializers的DRF是否可以实现? I'm mostly interested in seeing an example to reproduce if possible. 如果可能,我最想看到一个可以重现的示例。

Here are my models: 这是我的模型:

class Grandparent(Model):
    g_name = CharField(max_length=10)
    parent = ForeignKey('Parent')

class Parent(Model):
    p_name = CharField(max_length=10)
    child = ForeignKey('Child')

class Child(Model):
    c_name = CharField(max_length=10)

Here are my serializers: 这是我的序列化器:

class ChildSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Child
        fields = ('id', 'c_name')

class ParentSerializer(serializers.ModelSerializer):
    child = ChildSerializer()

    def create(self, validated_data):
        child_data = validated_data.pop('child')
        child, _ = models.Child.objects.get_or_create(**child_data)
        return models.Parent.objects.create(child=child, **validated_data)

    class Meta:
        model = models.Parent
        fields = ('id', 'p_name', 'child')

class GrandparentSerializer(serializers.ModelSerializer):
    parent = ParentSerializer()

    class Meta:
        model = models.Grandparent
        fields = ('id', 'g_name', 'parent')

Here is my grandparent view: 这是我的祖父母观点:

class GrandparentList(generics.ListCreateAPIView):
    queryset = models.Grandparent.objects.all()
    serializer_class = serializers.GrandparentSerializer

Here is the error I get when I try to post to the Grandparent view: 这是我尝试发布到祖父母视图时遇到的错误:

AttributeError at /grandparents/ 'list' object has no attribute 'get' / grandparents /“列表”对象中的AttributeError没有属性“ get”

Issue we found was that is a bug in the form front-end provided by DRF. 我们发现的问题是DRF提供的表单前端存在错误。 Nested serializer behaved correctly when called directly over HTTP. 直接通过HTTP调用时,嵌套序列化程序的行为正确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM