python - 不同表上的 after_insert 事件

标签 python sqlalchemy flask-sqlalchemy

我有表 A 和表 B,我想在表 A 事件中添加/更新/删除表 B 中的列。我尝试了以下方法:

  1. Mapper 事件 a.k.a @event.listens_for(SomeClass, 'before_insert')

文档说明

Mapper-level flush events are designed to operate on attributes local to the immediate object being handled and via SQL operations with the given Connection only... Operations that are not supported in mapper events include: Session.add() Session.delete()... Mapped relationship attribute set/del events

这限制了我对其他表的操作。例如,

def after_insert_listener(mapper, connection, target):
    target.value = "New Value"

时工作得很好
def after_insert_listener(mapper, connection, target):
    target.child.count += 1

没有成功。放入 db.session.commit() 给我这个错误

ResourceClosedError: This transaction is closed

我尝试使用 SessionEvents.before_flush(),但它既不能附加到特定模型,也不知道如何使用它。

  1. Flask-SQLAlchemy 信号

我尝试使用 models_committed 信号:

@models_committed.connect_via(app)
def on_models_committed(sender, changes):
    for obj, change in changes:
        if change == 'delete' and hasattr(obj, '__after_delete__'):
            obj.__after_delete__()
        elif change == 'update' and hasattr(obj, '__after_update__'):
            obj.__after_update__()
        elif change == 'insert' and hasattr(obj, '__after_insert__'):
            obj.__after_insert__()

class TableA(db.Model):
    def __after_insert__(self):
        self.child.count += 1
        self.value = "New Value"
        db.session.commit()

这给了我

InvalidRequestError: This session is in 'committed' state; no further SQL can be emitted within this transaction.

如何在插入另一个模型后更新模型的实例?

最佳答案

你可以试试这个,

        @event.listens_for(B, "after_insert")
        def after_insert_listener(mapper, connection, target):
            A_table = A.__table__
            connection.execute(
                    A_table.update().
                     where(A_table.id==target.a_table.id). # Do Foreign key join porperly 
                     values(value='New Value')
            )

关于python - 不同表上的 after_insert 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27902374/

相关文章:

python neurolab - 我们可以用许多输入部分进行增量训练吗?

python - 在电脑上查找文件并替换字符串会删除整个文件

python - Flask Sql-alchemy 不会删除 alembic 创建的表

python sqlalchemy 性能?

python - 如何在 SQLAlchemy 中建立与无类值的关系?

python - 在 flask 迁移或 alembic 迁移中创建种子数据

使用 Kill 进程进行 Python 测试

Python:在 "lambda"内定义变量

python - SQLAlchemy 嵌套 CTE 查询

python - 为什么 SQLAlchemy/associationproxy 会复制我的标签?