[英]Bulk insert of list of dictionary
I have defined my model class like below:我已经定义了我的模型类,如下所示:
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
I have created a session using below code using which I am doing most of my sql operations:我使用下面的代码创建了一个会话,我正在使用它执行我的大部分 sql 操作:
def get_session():
engine = create_engine('postgresql+psycopg2://postgres:postgres@localhost/db')
Session = sessionmaker(engine)
return Session()
I have my list of dictionary which I want to insert as a bulk insert.我有我想作为批量插入插入的字典列表。
In documentation , I can see where I can insert using something like below:在文档中,我可以看到可以使用以下内容插入的位置:
connection.execute(table.insert(), [
{'id':'12','name':'a','lang':'eng'},
{'id':'13','name':'b','lang':'eng'},
{'id':'14','name':'c','lang':'eng'},
]
)
My question is how can I perform such operation using my model class in the way I have provided the mapping.我的问题是如何以我提供映射的方式使用我的模型类执行此类操作。
Something like this does not work:像这样的东西不起作用:
conn.execute(MedicalPlans.insert(), list_of_dict)
The table of the mapped class should be available as映射类的表应该可用
MyTable.__table__
hence MedicalPlan.__table__.insert()
should work.因此
MedicalPlan.__table__.insert()
应该可以工作。
There are other options in the question linked to by Ilja, but most are not as efficient - bulk_insert_mappings
would come close. Ilja 链接到的问题中还有其他选项,但大多数都没有那么高效
bulk_insert_mappings
会很接近。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.