Reputation: 69
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'
Upvotes: 1
Views: 1418
Reputation: 69
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.
Upvotes: 1