Updating multiple columns in Sqlalchemy

社会主义新天地 提交于 2019-12-06 13:35:43

Multiple columns can be updated using the Session as:

def update_table(session, val1, val2, val3):
  session.query(Table).filter_by(col=val1).update(dict(col2=val2,col3=val3))
  session.commit()

you can write more generic function which will accept your table object, WHERE criteria and the actual update values. Something like

def get_update_query(table_name, where_vals, update_vals):
  query = table_name.update()
  for k, v in where_vals.iteritems():
    query = query.where(getattr(table_name.c, k) == v)
  return query.values(**update_vals)

table = YourTable
where_vals = {'col1': 'foo', 'col2': 'bar'}
update_vals = {'col1': 'foo_updated', 'col2': 'bar_updated'}
res = get_update_query(YourTable, where_vals, update_vals)

# UPDATE "YourTable" SET col1=:col1, col2=:col2 WHERE "YourTable".col1 = :col1_1 AND "YourTable".col2 = :col2_1
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!