我想在模型插入数据库后进行一些数据库操作。所以我为此做了一个钩子:
@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__()
在模特中我有:
def __commit_insert__(self):
result = Model.query.filter(...).one()
执行此代码时,会发生以下错误:
sqlalchemy.exc.InvalidRequestError: This session is in 'committed' state; no further SQL can be emitted within this transaction.
如何避免这种情况?在__commit_insert__方法中,我需要插入记录的主键,因此对于本例,本机事件" after_insert"和" after_flush" SQLAlchemy不适合