Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update data of one column for all rows in SqlAlchemy?

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

like image 284
Dipnesh Parakhiya Avatar asked Jul 07 '16 10:07

Dipnesh Parakhiya


2 Answers

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.

like image 141
antonio_antuan Avatar answered Sep 18 '22 06:09

antonio_antuan


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

like image 33
pcko1 Avatar answered Sep 21 '22 06:09

pcko1