使用SQLAlchemy从反射表中删除行 [英] Deleted rows from reflected table with SQLAlchemy

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

问题描述

我有一个要从中删除数据的表。我一直在使用Session()对象来查询数据,它工作得很好。但是当我删除数据列表时,它会失败。

I have a table that I'm trying to delete data from. I have been using a Session() object to query data, and it works just fine. But when I go to delete a list of data, it fails.

# load engine and reflect.
engine = create_engine("...")
metadata = MetaData()
Session = sessionmaker(autoflush=True, autocommit=True)
Session.configure(bind=engine)
session = Session()
metadata.reflect(bind=engine)

# queries work.
table = Table("some_table", metadata, autoload_with=engine)
session.query(table).filter(table.c.column.between(dobj1,dobj2)).all()

# deletes do not.
session.query(table).filter(table.c.column.in_([1,2,3,4,5])).delete()

当我尝试删除一排行时,得到以下信息:

When I try to delete a bunch of rows, I get this:

File "/virtualenv/lib/python2.7/site-packages/sqlalchemy/orm/persistence.py", line 1180, in _do_pre_synchronize
    target_cls = query._mapper_zero().class_
AttributeError: 'Table' object has no attribute 'class_'

我尝试了这个问题的方法,但是它给了我此错误:

I tried this question's method, but it gives me this error:

File "/virtualenv/lib/python2.7/site-packages/sqlalchemy/sql/base.py", line 385, in execute
    raise exc.UnboundExecutionError(msg)
sqlalchemy.exc.UnboundExecutionError: This None is not directly bound to a Connection or Engine.Use the .execute() method of a Connection or Engine to execute this construct.

我尝试使用 automap_base()将其映射到声明性库,但是我只是遇到了不同的错误。

I tried to map it to a declarative base with automap_base(), but I just got different errors.

如何从已经建立的会话中加载的表中删除行?

How can I delete rows from the table I loaded in the session I already have established?

推荐答案

查询接口是SQLAlchemy ORM的一部分,未映射

The query interface is part of the SQLAlchemy ORM, and table isn't mapped to a class.

与您链接的答案使用绑定的元数据(在现代SQLAlchemy中已被淘汰)。以下应该可以工作:

The answer you linked to uses bound metadata (discouraged in modern SQLAlchemy). The following should work:

stmt = table.delete().where(table.c.column.in_([1,2,3,4,5]))

with engine.connect() as conn:
    conn.execute(stmt)

编辑:

我意识到您可以这样做:

I realised that you can do this:

session.query(table).filter(table.c.column.in_([1,2,3,4,5])) \
    .delete(synchronize_session=False)

这篇关于使用SQLAlchemy从反射表中删除行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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