SQLAlchemy: How do you delete multiple rows without querying

PythonOrmSqlalchemy

Python Problem Overview


I have a table that has millions of rows. I want to delete multiple rows via an in clause. However, using the code:

session.query(Users).filter(Users.id.in_(subquery....)).delete()

The above code will query the results, and then execute the delete. I don't want to do that. I want speed.

I want to be able to execute (yes I know about the session.execute):Delete from users where id in ()

So the Question: How can I get the best of two worlds, using the ORM? Can I do the delete without hard coding the query?

Python Solutions


Solution 1 - Python

Yep! You can call delete() on the table object with an associated where clause.

Something like this:

stmt = Users.__table__.delete().where(Users.id.in_(subquery...))

(and then don't forget to execute the statement: engine.execute(stmt))

source

Solution 2 - Python

To complete dizzy's answer:

delete_q = Report.__table__.delete().where(Report.data == 'test')
db.session.execute(delete_q)
db.session.commit()

Solution 3 - Python

The below solution also works, if developers do not want to execute a plain vanilla query.

session.query(Users).filter(Users.id.in_(subquery....)).delete(synchronize_session=False)

Solution 4 - Python

New syntax

from sqlalchemy import delete

statement = delete(User).where(User.id.in_(...))
session.exec(statement)

https://docs.sqlalchemy.org/en/14/core/dml.html?highlight=delete

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionsupreme PoobaView Question on Stackoverflow
Solution 1 - PythondizzyfView Answer on Stackoverflow
Solution 2 - PythonMickaelView Answer on Stackoverflow
Solution 3 - PythonOjus sangoiView Answer on Stackoverflow
Solution 4 - PythonAngelView Answer on Stackoverflow