Get the inserted primary key ids using bulk_save_objects

岁酱吖の 提交于 2021-02-07 21:54:45

问题


How can I get the inserted Ids (primary key generated) after using session.bulk_save_objects?

I tried this:

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)

The ids are None. The rows are successfully inserted.


回答1:


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)



回答2:


A more performant way to do this rather than using bulk_save_objects which emits an insert statement per value is to use from sqlalchemy.dialects.postgresql.insert with a returning clause.

insert_stmt = insert(Table).values(dictionary_mappings).returning(Table.id)
ids = db.session.execute(insert_stmt).fetchall()


来源:https://stackoverflow.com/questions/51131407/get-the-inserted-primary-key-ids-using-bulk-save-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!