I want to do some database manipulations after model inserted into the database. So I made a hook for this:
@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__()
In model I have:
def __commit_insert__(self):
result = Model.query.filter(...).one()
And when this code is executed, the following error occurs:
sqlalchemy.exc.InvalidRequestError: This session is in 'committed' state; no further SQL can be emitted within this transaction.
How to avoid this? In the method __commit_insert__ I need the primary key of the inserted record, so for this case the native events "after_insert" and "after_flush" of SQLAlchemy is not suitable