简体   繁体   中英

Double-nested serializers with Django Rest Framework

Is this possible with DRF using ModelSerializers? 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'

Issue we found was that is a bug in the form front-end provided by DRF. Nested serializer behaved correctly when called directly over HTTP.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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