如何在没有ORM的情况下使用SQLAlchemy查询从表中删除行? [英] How to delete rows from a table using an SQLAlchemy query without ORM?

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

问题描述

我正在编写一个快速且肮脏的维护脚本,以删除一些行,并希望避免不得不将我的ORM类/映射从主项目移过来.我有一个类似于以下查询:

I'm writing a quick and dirty maintenace script to delete some rows and would like to avoid having to bring my ORM classes/mappings over from the main project. I have a query that looks similar to:

address_table = Table('address',metadata,autoload=True)
addresses = session.query(addresses_table).filter(addresses_table.c.retired == 1)

根据我已阅读的所有内容,如果我使用的是ORM(而不是仅"表)并传入类似以下内容的话:

According to everything I've read, if I was using the ORM (not 'just' tables) and passed in something like:

addresses = session.query(Addresses).filter(addresses_table.c.retired == 1)

我可以在查询中添加.delete(),但是当我尝试仅使用表执行此操作时,我会抱怨:

I could add a .delete() to the query, but when I try to do this using only tables I get a complaint:

File "/usr/local/lib/python2.6/dist-packages/sqlalchemy/orm/query.py", line 2146, in delete
    target_cls = self._mapper_zero().class_
AttributeError: 'NoneType' object has no attribute 'class_'

这是有意义的,因为它是一个表,而不是一个类.在谈到SQLAlchemy时,我已经很环保了,该怎么办?

Which makes sense as its a table, not a class. I'm quite green when it comes to SQLAlchemy, how should I be going about this?

推荐答案

查看一些我做了类似操作的代码,我相信这会满足您的要求.

Looking through some code where I did something similar, I believe this will do what you want.

d = addresses_table.delete().where(addresses_table.c.retired == 1)
d.execute()

在表对象上调用delete()会给您一个sql.expression(如果有内存的话),然后您可以执行.我在上面假设表已绑定到一个连接,这意味着您可以在其上调用execute().如果没有,您可以在连接上将d传递给execute(d).

Calling delete() on a table object gives you a sql.expression (if memory serves), that you then execute. I've assumed above that the table is bound to a connection, which means you can just call execute() on it. If not, you can pass the d to execute(d) on a connection.

此处中查看文档>.

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

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