I'm trying to create an object with nested serialization so other objects that relate to it are also created. I've overridden the create() method for ModelSerializer and the main object is created successfully.
def create(self, validated_data):
post_data = validated_data.pop('post_set')
big_post = BigPost.objects.create(**validated_data) // This works
for post in post_data:
e = PostSerializer(data=post)
if e.is_valid():
e.save()
else:
print(e.errors) // Prints 'Incorrect type' error
return big_post
However, when trying to create the nested object (Post), I get this error:
{'note': ['Incorrect type. Expected pk value, received Note.']}
'note' is a field of the PostSerializer as shown below:
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = ('id', 'note', 'title', 'description')
I am aware that default behaviour of ModelSerializer is to create PrimaryKeyRelatedField for any related fields of the model. But, I don't know why an instance is being created when the data submitted is just a PK like so: {"note":3, ....}
If your serializers defined properly, you don't need to deserialize validated_data for the second time.
Docs: http://www.django-rest-framework.org/api-guide/serializers/#writable-nested-representations
Try this code:
class PostSerializer(serializers.ModelSerializer):
...
class BigPostSerializer(serializers.ModelSerializer):
posts = PostSerializer(source='post_set', many=True)
def create(self, validated_data):
post_data = validated_data.pop('post_set')
big_post = BigPost.objects.create(**validated_data)
for post in post_data:
e = Post.objects.create(bigpost=big_post, **post)
return big_post
bigpost - is the name of foreign key to BigPost.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With