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

查看:19
本文介绍了如何使用没有 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天全站免登陆