gpt4 book ai didi

python - 不同表上的 after_insert 事件

转载 作者:行者123 更新时间:2023-11-28 18:39:42 24 4
gpt4 key购买 nike

我有表 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com