Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

python - How can i bulk create in django rest serializer

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...