【问题标题】:Deleted rows from reflected table with SQLAlchemy使用 SQLAlchemy 从反射表中删除的行
【发布时间】:2016-06-11 01:40:03
【问题描述】:

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

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

【问题讨论】:

    标签: python postgresql sqlalchemy


    【解决方案1】:

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

    【讨论】:

    • 所以它作为查询的一部分工作,因为它不需要是映射类,它只需要描述表对象。但是因为没有映射,所以不能在上面任意执行语句?
    • 所以编辑成功了,同步会话的具体内容是什么?
    • @mynameismevin 会话使用工作单元模式来跟踪您未使用的 ORM 对象。
    • 明白了!我只是将会话用作连接共享的一种方式。由于我并不特别关心数据模型,这仍然是一种将非 ORM 方法用于 SQLAlchemy 的明智方法吗?
    • 在第一个代码块中使用引擎已经使用了连接池。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-17
    • 2012-03-24
    • 2011-06-22
    • 1970-01-01
    • 2018-12-15
    • 2012-04-10
    • 1970-01-01
    相关资源
    最近更新 更多