Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the inserted primary key ids using bulk_save_objects

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.

like image 667
el_pup_le Avatar asked Jul 17 '26 08:07

el_pup_le


2 Answers

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)
like image 169
PythonUser Avatar answered Jul 21 '26 19:07

PythonUser


A more performant way to do this rather than using bulk_save_objects which emits an insert statement per value is to use 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()
like image 25
Scott Thompson Avatar answered Jul 21 '26 17:07

Scott Thompson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!