[英]Bulk insert of list of dictionary
我已经定义了我的模型类,如下所示:
class MedicalPlan(Base):
__tablename__ = "medical_plans"
id = Column(Integer, nullable=False , primary_key=True)
issuer_id = Column(Integer, ForeignKey('issuers.id'), nullable=False)
service_area_id = Column(Integer).... and so
我使用下面的代码创建了一个会话,我正在使用它执行我的大部分 sql 操作:
def get_session():
engine = create_engine('postgresql+psycopg2://postgres:postgres@localhost/db')
Session = sessionmaker(engine)
return Session()
我有我想作为批量插入插入的字典列表。
在文档中,我可以看到可以使用以下内容插入的位置:
connection.execute(table.insert(), [
{'id':'12','name':'a','lang':'eng'},
{'id':'13','name':'b','lang':'eng'},
{'id':'14','name':'c','lang':'eng'},
]
)
我的问题是如何以我提供映射的方式使用我的模型类执行此类操作。
像这样的东西不起作用:
conn.execute(MedicalPlans.insert(), list_of_dict)
映射类的表应该可用
MyTable.__table__
因此MedicalPlan.__table__.insert()
应该可以工作。
Ilja 链接到的问题中还有其他选项,但大多数都没有那么高效bulk_insert_mappings
会很接近。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.