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

# 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()

当我试图删除一堆行时,我会得到:
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_'

我尝试了this question's方法,但它给了我一个错误:
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()将它映射到一个声明基,但是我得到了不同的错误。
如何从已建立的会话中加载的表中删除行?

最佳答案

查询接口是SQLAlchemy ORM的一部分,并且table没有映射到类。
链接到的答案使用绑定元数据(在现代SQLAlchemy中不鼓励)。以下方法应该有效:

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

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

编辑:
我意识到你可以做到:
session.query(table).filter(table.c.column.in_([1,2,3,4,5])) \
    .delete(synchronize_session=False)

10-07 13:21
查看更多