使用SQLAlchemy从反射表中删除行

时间:2016-06-11 01:40:03

标签: python postgresql sqlalchemy

我有一张表,我试图从中删除数据。我一直在使用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()的声明基础,但我只是遇到了不同的错误。

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

1 个答案:

答案 0 :(得分:4)

查询接口是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)