How to update data of one column for all rows in SqlAlchemy?
2021 Answer
As of sqlalchemy==1.4
and the upcoming release of 2.0
, the recommended way of performing an UPDATE
is via the SA-builtin update
function, rather than the .update
method.
Example:
from sqlalchemy import update
uid=1
# MY_CONDITION is whatever condition triggers the change in status value
update(Uninstall).where(MY_CONDITION).values(status=uid)
If you want to change the status
value to be equal to uid
for all columns, then you can simply do it unconditionally:
update(Uninstall).values(status=uid)
Finally, don't forget to commit:
session.commit()
Source: https://docs.sqlalchemy.org/en/14/core/dml.html?highlight=update#sqlalchemy.sql.expression.update
The suggested is not optimized. You can use the options to update: 1.
for row in Uninstall.query: # all() is extra
row.status = new_status
Session.commit()
If there are lots of rows, it can be faster, but it will invoke UPDATE
for every row. Not good, is it?
2.
Uninstall.query.update({Uninstall.status: new_status})
Session.commit()
Invokes only one UPDATE
query for all rows.