使用python字典列表批量更新表中的特定列(不是全部)

2024-06-25 23:41:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用python字典列表在表上执行批量更新映射,这些字典有选择性的列作为键及其值

下面是table类和dict的python列表

class KpcComputation(BASE):
    """KpcComputation model class"""
    __tablename__ = 'kpc_computation_v2'
    __table_args__ = {'useexisting': True}

    kc_rs_id = Column('kc_rs_id', Integer, ForeignKey("review_sentences_v2.rs_id"))
    kc_kpc_id = Column('kc_kpc_id', Integer, ForeignKey("kpc_v2.kpc_id"))
    kc_kpc_score = Column('kc_kpc_score', Float)
    kc_sentiment = Column('kc_sentiment', String)
    kc_sentiment_score = Column('kc_sentiment_score', Float)
    kc_last_updated_date_time = Column(
        DateTime,
        onupdate=datetime.datetime.now,
        default=datetime.datetime.now
    )
    __mapper_args__ = {
        'primary_key': [kc_rs_id, kc_kpc_id]}

dict_data = [{'kc_rs_id': 1194773, 'kc_sentiment': 'neutral', 'kc_sentiment_score': 2.0},
             {'kc_rs_id': 1194774, 'kc_sentiment': 'positive', 'kc_sentiment_score': 3.0},
             {'kc_rs_id': 1550643, 'kc_sentiment': 'negative', 'kc_sentiment_score': 1.0}]

更新操作只能在kc_情绪和kc_情绪得分上进行,只要kc_rs_id在表和dict的python列表之间匹配。我尝试了以下方法进行更新

self.session.bulk_update_mappings(KpcComputation, dict_data)
self.session.commit()

我的理解是,上述语句将在kc_rs_id匹配的任何位置使用新值更新行。但我觉得我错过了什么

我尝试过寻找对特定列执行批量更新的方法,但一些答案建议对所有列使用值(用一些默认值填充不属于insterest的列),这不是我想要的。我是SQLAlchemy的新手,所以不知道如何准确地实现这一点。有没有更好的方法可以做到这一点?如有任何建议,我们将不胜感激


Tags: 方法id列表datetime字典column批量dict