12

I am using Flask and a SQLAlchemy extension. Also I am using the declarative way to write my models as described in the extension's documentation.

For one of my models, I have some code I need to run after a new row has been inserted, updated or deleted. I was wondering how to do it? Ideally I would just add functions to the model.

1 Answer 1

22

Look at SQLAlchemy's Mapper Events. You can bind a callback function to the after_insert, after_update, and after_delete events.

Example:

from sqlalchemy import event

def after_insert_listener(mapper, connection, target):
    # 'target' is the inserted object
    print(target.id_user)

event.listen(User, 'after_insert', after_insert_listener)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.