How can i bulk create in django rest serializer

2019-02-23 19:11发布

I used to use allow_add_remove=True which was availabe in django rest 2.0 for writing nestable serializer but its not available in 3.0 and i am having hard time implementing it.

I want to do something like this

class UserSerialzier():
    project = ProjectSerilaizer(many=True, allow_add_remove=True, read_only=False)


class ProjectSerialzier():
    ideas = IdeaSerilaizer(many=True, allow_add_remove=True, read_only=False)
    sources = SourceSerilaizer(many=True, allow_add_remove=True, read_only=False)

class IdeaSerialzier():
    pass

class SourceSerialzier():
    pass      

Now i am not able to know how can i implement the allow_add_remove behavior in DRF 3.0

I am confused that do i need to override create and update method of UserSerializer

or i need to create separate IdeaListSerializer for every model

class IdeaListSerializer(serializers.ListSerializer):
    def create(self, validated_data):
        ideas = [Idea(**item) for item in validated_data]
        return Ideas.objects.bulk_create(books)

1条回答
你好瞎i
2楼-- · 2019-02-23 19:45

Yes you do need to override create and update methods of your UserSerializer.

I've spent a lot of time trying to make nested writable serializers work with DRF 2.x and the more I fixed issues the more issues were risen with corner use cases.

Therefore Tom decided that it should be left up to the developer to handle the creation and updates.

The documentation provides an example for a 1 nesting level creation but it's the same for update and/or with more nesting level

查看更多
登录 后发表回答