使用bulk_save_objects获取插入的主键ID [英] Get the inserted primary key ids using bulk_save_objects
本文介绍了使用bulk_save_objects获取插入的主键ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用 session.bulk_save_objects
后如何获取插入的ID(生成的主键)?
How can I get the inserted Ids (primary key generated) after using session.bulk_save_objects
?
我尝试过:
for x in y:
obj = Post(...)
obj_list.append(obj)
session.bulk_save_objects(obj_list)
session.commit()
for i in obj_list:
print(i.id)
id为None.这些行已成功插入.
The ids are None. The rows are successfully inserted.
推荐答案
您需要在bulk_save_object方法中添加 return_defaults = True
,以获取记录的主键
you need to add return_defaults = True
in bulk_save_object method like below to get primary key of records
for x in y:
obj = Post(...)
obj_list.append(obj)
session.bulk_save_objects(obj_list,return_defaults = True)
session.commit()
for i in obj_list:
print(i.id)
这篇关于使用bulk_save_objects获取插入的主键ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文