如何对许多对象使用 bulk_create() 来执行 save() 操作
how to use the bulk_create() for many objects to do the save() operation
我有很多对象要存入数据库,代码如下:
def addSthGroups(groups):
for group in groups: # each group is an object
group.addSth()
group.save()
而且现在,一个一个保存所有的对象需要很多时间。所以我的问题是:是否有一种更有效的方法来收集所有对象,只需调用一次 save() ,它可能会加快处理时间,据我所知, bulk_create 听起来很适合处理这种情况,可以有人举这个代码的例子吗?或者有什么好的建议?
你可以只做 Group.objects.bulk_create(groups)
,假设 Group
是模型名称。
bulk_create
不会调用 save()
。引用 django doc:
The model's save()
method will not be called, and the pre_save
and
post_save
signals will not be sent.
我有很多对象要存入数据库,代码如下:
def addSthGroups(groups):
for group in groups: # each group is an object
group.addSth()
group.save()
而且现在,一个一个保存所有的对象需要很多时间。所以我的问题是:是否有一种更有效的方法来收集所有对象,只需调用一次 save() ,它可能会加快处理时间,据我所知, bulk_create 听起来很适合处理这种情况,可以有人举这个代码的例子吗?或者有什么好的建议?
你可以只做 Group.objects.bulk_create(groups)
,假设 Group
是模型名称。
bulk_create
不会调用 save()
。引用 django doc:
The model's
save()
method will not be called, and thepre_save
andpost_save
signals will not be sent.