python - 使用 SQLAlchemy 从反射表中删除行

标签 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() 将其映射到声明性基础,但我遇到了不同的错误。

如何从已建立的 session 中加载的表中删除行?

最佳答案

查询接口(interface)是 SQLAlchemy ORM 的一部分,table 未映射到类。

您链接到的答案使用绑定(bind)元数据(在现代 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)

关于python - 使用 SQLAlchemy 从反射表中删除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37759161/

相关文章:

python - SQLAlchemy M2M关系查询

python - 将元组提取到 pandas DataFrame 中的行中

sql - 在 Postgres 中的数组字段中搜索

ruby-on-rails - 如何自动将 OSM 数据集加载到 rake db :create or migrate 上的 rails postgresql db

docker - Jupyterhub (TLJH) : Failure setting up Development Environment: "Failed to start jupyterhub.service."

python - SQLAlchemy:是否知道模型对象的字段名称和值?

python - 无法编码 <type 'datetime.date' > 对象

Python:使用主函数

python - 在python中使用for循环生成mySQL插入语句

postgresql - 如何从 postgresql 函数返回表的不确定数字列?