SQLAlchemy: How do you delete multiple rows without querying

∥☆過路亽.° 提交于 2020-11-30 02:58:59

问题


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?


回答1:


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




回答2:


To complete dizzy's answer:

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



回答3:


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)


来源:https://stackoverflow.com/questions/39773560/sqlalchemy-how-do-you-delete-multiple-rows-without-querying

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