Vla*_*yuk 6 python sqlalchemy flask flask-sqlalchemy
我想在将模型插入数据库后进行一些数据库操作。所以我为此做了一个勾子:
@models_committed.connect
def on_models_committed(sender, changes):
for obj, change in changes:
if change == 'delete' and hasattr(obj, '__commit_delete__'):
obj.__commit_delete__()
elif change == 'insert' and hasattr(obj, '__commit_insert__'):
obj.__commit_insert__()
elif change == 'update' and hasattr(obj, '__commit_update__'):
obj.__commit_update__()
Run Code Online (Sandbox Code Playgroud)
在模型中,我有:
def __commit_insert__(self):
result = Model.query.filter(...).one()
Run Code Online (Sandbox Code Playgroud)
并且当执行此代码时,会发生以下错误:
sqlalchemy.exc.InvalidRequestError: This session is in 'committed' state; no further SQL can be emitted within this transaction.
Run Code Online (Sandbox Code Playgroud)
如何避免这种情况?在方法__commit_insert__中,我需要插入记录的主键,因此对于这种情况,SQLAlchemy的本机事件“ after_insert”和“ after_flush”不适合