我如何在Django Rest序列化器中批量创建 [英] How can i bulk create in django rest serializer
问题描述
我曾经使用 allow_add_remove = True ,它在django rest 2.0中可用,用于编写可嵌套的序列化程序,但在3.0中不可用,我很难实现它。
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.
我想做这样的事情
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
现在我不知道如何实现allow_add_remove行为在DRF 3.0中
Now i am not able to know how can i implement the allow_add_remove behavior in DRF 3.0
我很困惑,我是否需要覆盖 create
和 update
UserSerializer的方法
I am confused that do i need to override create
and update
method of UserSerializer
或者我需要创建sep每个模型的价目表IdeaListSerializer
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)
推荐答案
是的,您确实需要覆盖 create
和 update $您的
UserSerializer
的c $ c>方法。
Yes you do need to override create
and update
methods of your UserSerializer
.
我花了很多时间试图使嵌套可写序列化程序可与DRF 2.x一起使用,而我修复的问题越多,出现用例的问题就越多。
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.
因此,Tom决定将其留给开发人员来处理创建和更新。
Therefore Tom decided that it should be left up to the developer to handle the creation and updates.
文档为创建1嵌套级别提供了一个示例,但对于更新和/或wi来说都是相同的嵌套级别更高
The documentation provides an example for a 1 nesting level creation but it's the same for update and/or with more nesting level
这篇关于我如何在Django Rest序列化器中批量创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!