SQLAlchemy:如何在不查询的情况下删除多行 [英] SQLAlchemy: How do you delete multiple rows without querying

查看:52
本文介绍了SQLAlchemy:如何在不查询的情况下删除多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有数百万行的表.我想通过 in 子句删除多行.但是,使用代码:

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.

我希望能够执行(是的,我知道 session.execute):Delete from users where id in ()

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

问题是:如何使用 ORM 获得两全其美的效果?我可以在不对查询进行硬编码的情况下进行删除吗?

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?

推荐答案

是的!您可以使用关联的 where 子句对表对象调用 delete().

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

像这样:

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

(然后不要忘记执行语句:engine.execute(stmt))

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

来源

这篇关于SQLAlchemy:如何在不查询的情况下删除多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆