SQLAlchemy "event.listen" for all models

In newer versions of sqlalchemy (1.2+), the following event targets are available:

  • mapped classes (that is, subscribe to every model)
  • unmapped superclasses (that is, Base, and mixins, using the propagate=True flag)
  • Mapper objects
  • Mapper class itself

So, in order to listen to all instance events, you can listen on Mapper itself:

from typing import Set, Optional

import sqlalchemy as sa
import sqlalchemy.orm.query
import sqlalchemy.event

@sa.event.listens_for(sa.orm.Mapper, 'refresh', named=True)
def on_instance_refresh(target: type, 
                        context: sa.orm.query.QueryContext, 
                        attrs: Optional[Set[str]]):
    ssn: sqlalchemy.orm.Session = context.session
    print(target, attrs)

this way you will get an app-wide event listener. If you want to only listen to your own models, use the Base class


Inherit all your models from the base class and subscribe to that base class:

event.listen(MyBaseMixin, 'before_insert', get_created_by_id, propagate=True)
event.listen(MyBaseMixin, 'before_update', get_updated_by_id, propagate=True)

See more on Mixin and Custom Base Classes