Updating multiple columns in Sqlalchemy

怎甘沉沦 提交于 2019-12-08 02:21:43

问题


I have an app that runs on flask and uses sqlalchemy to interact with the data base. I want to update the columns of a table with the user specified values. The query that I am using is

def update_table(value1, value2, value3):
     query = update(Table).where(Table.column1 == value1).values(Table.column2 = value2, Table.column3 = value3)

I am not sure if the way I am passing values is correct. Also the Table.column2/3 i=gives error saying Can't assign to function call . Where column2/3 are not functions, they're field names. So, how do I update multiple values and why is it giving error here?

PS: I referred the sqlalchemy doc


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/35805600/updating-multiple-columns-in-sqlalchemy

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