[英]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.