For single record update, I have tried the following code and it's working.
uid=1
info = Info.query.filter_by(id=uid).first()
info.sold_status ='1'
db.session.add(info)
db.session.commit()
Now I want to update one column for multiple rows. I have tried:
for row in db.session.query(Uninstall.status).all():
print row.status
abc=row.status
abc=uid
db.session.add(row.status)
db.session.commit()
but it's not working.
Thanks in advance :)
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With