Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialization error: Incorrect type. Expected pk value, received Post

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, ....}

like image 862
zubhav Avatar asked Jan 29 '17 20:01

zubhav


1 Answers

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.

like image 86
Dmitry Shilyaev Avatar answered Oct 14 '22 10:10

Dmitry Shilyaev