【问题标题】:Bulk insert of list of dictionary字典列表的批量插入
【发布时间】:2019-03-21 10:12:12
【问题描述】:

我已经定义了我的模型类,如下所示:

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()

我有我想要作为批量插入插入的字典列表。

documentation 中,我可以使用以下内容查看可以插入的位置:

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)

【问题讨论】:

标签: python sqlalchemy


【解决方案1】:

映射类的表应该是可用的

MyTable.__table__

因此MedicalPlan.__table__.insert() 应该可以工作。


Ilja 所链接的问题中还有其他选项,但大多数都没有那么有效 - bulk_insert_mappings 会接近。

【讨论】:

  • conn.execute(MedicalPlan.__tablename__.insert(), list_of_dict) 给我'str' object has no attribute 'insert'
  • 通过仔细阅读答案,并与您刚刚写的内容进行比较。
  • 它有效..谢谢.. 想检查一下,我可以将它与我正在创建的 Session 对象一起使用吗??
  • @themaster 是的。 Session.execute。虽然你可能还需要一些肮脏的处理......
  • @AnttiHaapala 你能告诉我,如何用Session.execute 做到这一点?
猜你喜欢
  • 2018-10-27
  • 1970-01-01
  • 2019-08-30
  • 2022-10-18
  • 2019-10-17
  • 1970-01-01
  • 2021-06-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多