使用sqlalchemy进行批量更新

时间:2018-10-26 06:52:14

标签: python postgresql sqlalchemy

我有一个字典清单。

 [{'medical_plan_id': 1039481, u'hearing_aids': '', u'clinical_diagnostic_mri': u'20% coinsurance', u'emergency_room': u'20% coinsurance'}, {'medical_plan_id': 1039482, u'hearing_aids': '', u'clinical_diagnostic_mri': u'20% coinsurance', u'emergency_room': u'20% coinsurance'}]

我可以使用以下代码批量插入-

def write_plan_benefittodb(self, benefits_dict):
    try:
        count = benefits_dict.__len__()
        engine = create_engine('postgresql+psycopg2://postgres:postgres@localhost/test_db', use_batch_mode=True)
        conn = engine.connect()
        if count > 0:
            print ("Bulk update to database..")
            conn.execute(MedicalPlanBenefit.__table__.insert(), benefits_dict)
        else:
            print("No rows to update..")
        logging.info("Number of rows inserted. %s \n", benefits_dict.__len__())
    except Exception as e:
        print e
        logging.error("No records were updated due to following error . %s", e)
    finally:
        conn.close()

我想在Update()上使用模型MedicalPlanBenefit运行批量medical_plan_id。如何实现呢?

我的模型班:

class MedicalPlanBenefit(Base):
    __tablename__ = "medical_plan_benefits"

    id = Column(Integer, nullable=False, primary_key=True)
    medical_plan_id = Column(Integer)
    maximum_out_of_pocket_limit_single = Column(String)
    maximum_out_of_pocket_limit_family = Column(String)

在将硬编码绑定到values()之后,我能够进行更新。我不想这样做,因为列数是50秒钟。我想用我的字典列表来达到这个目的。任何建议。

stmt = MedicalPlanBenefit.__table__.update()\
                    .where(MedicalPlanBenefit.__table__.c.medical_plan_id == bindparam('med_plan_id'))\
                    .values({'emergency_room': bindparam('emergency_room')})
                conn.execute(stmt, benefits_dict)

0 个答案:

没有答案