使用SQLAlchemy ORM批量插入并返回主键 [英] Bulk insert with SQLAlchemy ORM and return primary keys
本文介绍了使用SQLAlchemy ORM批量插入并返回主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用bulk_save_objects
或bulk_insert_mappings
将字典列表插入表中.有什么方法可以获取每个条目带有主键的对象列表吗?
I am trying to insert a list of dictionaries into a table using bulk_save_objects
or bulk_insert_mappings
. Is there any way I can get the list of objects with primary key for each entry?
try:
cycle_object_list = []
for cycle in cycle_list:
period = Period()
for k, v in cycle.items():
setattr(period, k, v)
cycle_object_list.append(period)
db.session.bulk_save_objects(cycle_object_list)
db.session.commit()
print(cycle_object_list)
except Exception:
db.session.rollback()
raise
finally:
db.session.close()
我期望像[Period.49, Period.50, Period.51]
但是实际结果是[Period.None,Period.None,Period.None]
But the actual result is [Period.None, Period.None, Period.None]
推荐答案
查看全文