ORM Events

The ORM includes a wide variety of hooks available for subscription.

For an introduction to the most commonly used ORM events, see the section Tracking queries, object and Session Changes with Events. The event system in general is discussed at Events. Non-ORM events such as those regarding connections and low-level statement execution are described in Core Events.

Session Events

The most basic event hooks are available at the level of the ORM Session object. The types of things that are intercepted here include:

  • Persistence Operations - the ORM flush process that sends changes to the database can be extended using events that fire off at different parts of the flush, to augment or modify the data being sent to the database or to allow other things to happen when persistence occurs. Read more about persistence events at Persistence Events.

  • Object lifecycle events - hooks when objects are added, persisted, deleted from sessions. Read more about these at Object Lifecycle Events.

  • Execution Events - Part of the 2.0 style execution model, all SELECT statements against ORM entities emitted, as well as bulk UPDATE and DELETE statements outside of the flush process, are intercepted from the Session.execute() method using the SessionEvents.do_orm_execute() method. Read more about this event at Execute Events.

Be sure to read the Tracking queries, object and Session Changes with Events chapter for context on these events.

Object NameDescription

SessionEvents

Define events specific to Session lifecycle.

class sqlalchemy.orm.``SessionEvents

Define events specific to Session lifecycle.

e.g.:

  1. from sqlalchemy import event
  2. from sqlalchemy.orm import sessionmaker
  3. def my_before_commit(session):
  4. print("before commit!")
  5. Session = sessionmaker()
  6. event.listen(Session, "before_commit", my_before_commit)

The listen() function will accept Session objects as well as the return result of sessionmaker() and scoped_session().

Additionally, it accepts the Session class which will apply listeners to all Session instances globally.

  • Parameters

    • raw=False

      When True, the “target” argument passed to applicable event listener functions that work on individual objects will be the instance’s InstanceState management object, rather than the mapped instance itself.

      New in version 1.3.14.

    • restore_load_context=False

      Applies to the SessionEvents.loaded_as_persistent() event. Restores the loader context of the object when the event hook is complete, so that ongoing eager load operations continue to target the object appropriately. A warning is emitted if the object is moved to a new loader context from within this event if this flag is not set.

      New in version 1.3.14.

Class signature

class sqlalchemy.orm.SessionEvents (sqlalchemy.event.Events)

  • method sqlalchemy.orm.SessionEvents.after_attach(session, instance)

    Execute after an instance is attached to a session.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeSessionOrFactory, 'after_attach')
  2. def receive_after_attach(session, instance):
  3. "listen for the 'after_attach' event"
  4. # ... (event handling logic) ...
  5. ```
  6. This is called after an add, delete or merge.
  7. Note
  8. As of 0.8, this event fires off *after* the item has been fully associated with the session, which is different than previous releases. For event handlers that require the object not yet be part of session state (such as handlers which may autoflush while the target object is not yet complete) consider the new [`before_attach()`](#sqlalchemy.orm.SessionEvents.before_attach "sqlalchemy.orm.SessionEvents.before_attach") event.
  9. See also
  10. [`SessionEvents.before_attach()`](#sqlalchemy.orm.SessionEvents.before_attach "sqlalchemy.orm.SessionEvents.before_attach")
  11. [Object Lifecycle Events]($10c3a07c3c01c2c3.md#session-lifecycle-events)
  • method sqlalchemy.orm.SessionEvents.after_begin(session, transaction, connection)

    Execute after a transaction is begun on a connection

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeSessionOrFactory, 'after_begin')
  2. def receive_after_begin(session, transaction, connection):
  3. "listen for the 'after_begin' event"
  4. # ... (event handling logic) ...
  5. ```
  6. - Parameters
  7. - **session** – The target [`Session`]($2d92bd546622cf54.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session").
  8. - **transaction** – The [`SessionTransaction`]($2d92bd546622cf54.md#sqlalchemy.orm.SessionTransaction "sqlalchemy.orm.SessionTransaction").
  9. - **connection** – The [`Connection`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") object which will be used for SQL statements.
  10. See also
  11. [`SessionEvents.before_commit()`](#sqlalchemy.orm.SessionEvents.before_commit "sqlalchemy.orm.SessionEvents.before_commit")
  12. [`SessionEvents.after_commit()`](#sqlalchemy.orm.SessionEvents.after_commit "sqlalchemy.orm.SessionEvents.after_commit")
  13. [`SessionEvents.after_transaction_create()`](#sqlalchemy.orm.SessionEvents.after_transaction_create "sqlalchemy.orm.SessionEvents.after_transaction_create")
  14. [`SessionEvents.after_transaction_end()`](#sqlalchemy.orm.SessionEvents.after_transaction_end "sqlalchemy.orm.SessionEvents.after_transaction_end")
  • method sqlalchemy.orm.SessionEvents.after_bulk_delete(delete_context)

    Execute after ORM DELETE against a WHERE expression has been invoked.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeSessionOrFactory, 'after_bulk_delete')
  2. def receive_after_bulk_delete(delete_context):
  3. "listen for the 'after_bulk_delete' event"
  4. # ... (event handling logic) ...
  5. # DEPRECATED calling style (pre-0.9, will be removed in a future release)
  6. @event.listens_for(SomeSessionOrFactory, 'after_bulk_delete')
  7. def receive_after_bulk_delete(session, query, query_context, result):
  8. "listen for the 'after_bulk_delete' event"
  9. # ... (event handling logic) ...
  10. ```
  11. Deprecated since version 0.9: The `after_bulk_delete` event now accepts the arguments `delete_context`. Support for listener functions which accept the previous argument signature(s) listed above as “deprecated” will be removed in a future release.
  12. This is called as a result of the [`Query.delete()`]($3cf240505c8b4e45.md#sqlalchemy.orm.Query.delete "sqlalchemy.orm.Query.delete") method.
  13. - Parameters
  14. **delete\_context** –
  15. a “delete context” object which contains details about the update, including these attributes:
  16. > - `session` - the [`Session`]($2d92bd546622cf54.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session") involved
  17. >
  18. > - `query` -the [`Query`]($3cf240505c8b4e45.md#sqlalchemy.orm.Query "sqlalchemy.orm.Query") object that this update operation was called upon.
  19. >
  20. > - `result` the [`CursorResult`]($cd778e34cf5e4642.md#sqlalchemy.engine.CursorResult "sqlalchemy.engine.CursorResult") returned as a result of the bulk DELETE operation.
  21. >
  22. Changed in version 1.4: the update\_context no longer has a `QueryContext` object associated with it.
  23. See also
  24. [`QueryEvents.before_compile_delete()`](#sqlalchemy.orm.QueryEvents.before_compile_delete "sqlalchemy.orm.QueryEvents.before_compile_delete")
  25. [`SessionEvents.after_bulk_update()`](#sqlalchemy.orm.SessionEvents.after_bulk_update "sqlalchemy.orm.SessionEvents.after_bulk_update")
  • method sqlalchemy.orm.SessionEvents.after_bulk_update(update_context)

    Execute after an ORM UPDATE against a WHERE expression has been invoked.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeSessionOrFactory, 'after_bulk_update')
  2. def receive_after_bulk_update(update_context):
  3. "listen for the 'after_bulk_update' event"
  4. # ... (event handling logic) ...
  5. # DEPRECATED calling style (pre-0.9, will be removed in a future release)
  6. @event.listens_for(SomeSessionOrFactory, 'after_bulk_update')
  7. def receive_after_bulk_update(session, query, query_context, result):
  8. "listen for the 'after_bulk_update' event"
  9. # ... (event handling logic) ...
  10. ```
  11. Deprecated since version 0.9: The `after_bulk_update` event now accepts the arguments `update_context`. Support for listener functions which accept the previous argument signature(s) listed above as “deprecated” will be removed in a future release.
  12. This is called as a result of the [`Query.update()`]($3cf240505c8b4e45.md#sqlalchemy.orm.Query.update "sqlalchemy.orm.Query.update") method.
  13. - Parameters
  14. **update\_context** –
  15. an “update context” object which contains details about the update, including these attributes:
  16. > - `session` - the [`Session`]($2d92bd546622cf54.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session") involved
  17. >
  18. > - `query` -the [`Query`]($3cf240505c8b4e45.md#sqlalchemy.orm.Query "sqlalchemy.orm.Query") object that this update operation was called upon.
  19. >
  20. > - `values` The “values” dictionary that was passed to [`Query.update()`]($3cf240505c8b4e45.md#sqlalchemy.orm.Query.update "sqlalchemy.orm.Query.update").
  21. >
  22. > - `result` the [`CursorResult`]($cd778e34cf5e4642.md#sqlalchemy.engine.CursorResult "sqlalchemy.engine.CursorResult") returned as a result of the bulk UPDATE operation.
  23. >
  24. Changed in version 1.4: the update\_context no longer has a `QueryContext` object associated with it.
  25. See also
  26. [`QueryEvents.before_compile_update()`](#sqlalchemy.orm.QueryEvents.before_compile_update "sqlalchemy.orm.QueryEvents.before_compile_update")
  27. [`SessionEvents.after_bulk_delete()`](#sqlalchemy.orm.SessionEvents.after_bulk_delete "sqlalchemy.orm.SessionEvents.after_bulk_delete")
  • method sqlalchemy.orm.SessionEvents.after_commit(session)

    Execute after a commit has occurred.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeSessionOrFactory, 'after_commit')
  2. def receive_after_commit(session):
  3. "listen for the 'after_commit' event"
  4. # ... (event handling logic) ...
  5. ```
  6. Note
  7. The [`SessionEvents.after_commit()`](#sqlalchemy.orm.SessionEvents.after_commit "sqlalchemy.orm.SessionEvents.after_commit") hook is *not* per-flush, that is, the [`Session`]($2d92bd546622cf54.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session") can emit SQL to the database many times within the scope of a transaction. For interception of these events, use the [`SessionEvents.before_flush()`](#sqlalchemy.orm.SessionEvents.before_flush "sqlalchemy.orm.SessionEvents.before_flush"), [`SessionEvents.after_flush()`](#sqlalchemy.orm.SessionEvents.after_flush "sqlalchemy.orm.SessionEvents.after_flush"), or [`SessionEvents.after_flush_postexec()`](#sqlalchemy.orm.SessionEvents.after_flush_postexec "sqlalchemy.orm.SessionEvents.after_flush_postexec") events.
  8. Note
  9. The [`Session`]($2d92bd546622cf54.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session") is not in an active transaction when the [`SessionEvents.after_commit()`](#sqlalchemy.orm.SessionEvents.after_commit "sqlalchemy.orm.SessionEvents.after_commit") event is invoked, and therefore can not emit SQL. To emit SQL corresponding to every transaction, use the [`SessionEvents.before_commit()`](#sqlalchemy.orm.SessionEvents.before_commit "sqlalchemy.orm.SessionEvents.before_commit") event.
  10. - Parameters
  11. **session** – The target [`Session`]($2d92bd546622cf54.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session").
  12. See also
  13. [`SessionEvents.before_commit()`](#sqlalchemy.orm.SessionEvents.before_commit "sqlalchemy.orm.SessionEvents.before_commit")
  14. [`SessionEvents.after_begin()`](#sqlalchemy.orm.SessionEvents.after_begin "sqlalchemy.orm.SessionEvents.after_begin")
  15. [`SessionEvents.after_transaction_create()`](#sqlalchemy.orm.SessionEvents.after_transaction_create "sqlalchemy.orm.SessionEvents.after_transaction_create")
  16. [`SessionEvents.after_transaction_end()`](#sqlalchemy.orm.SessionEvents.after_transaction_end "sqlalchemy.orm.SessionEvents.after_transaction_end")
  • method sqlalchemy.orm.SessionEvents.after_flush(session, flush_context)

    Execute after flush has completed, but before commit has been called.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeSessionOrFactory, 'after_flush')
  2. def receive_after_flush(session, flush_context):
  3. "listen for the 'after_flush' event"
  4. # ... (event handling logic) ...
  5. ```
  6. Note that the session’s state is still in pre-flush, i.e. ‘new’, ‘dirty’, and ‘deleted’ lists still show pre-flush state as well as the history settings on instance attributes.
  7. Warning
  8. This event runs after the [`Session`]($2d92bd546622cf54.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session") has emitted SQL to modify the database, but **before** it has altered its internal state to reflect those changes, including that newly inserted objects are placed into the identity map. ORM operations emitted within this event such as loads of related items may produce new identity map entries that will immediately be replaced, sometimes causing confusing results. SQLAlchemy will emit a warning for this condition as of version 1.3.9.
  9. - Parameters
  10. - **session** – The target [`Session`]($2d92bd546622cf54.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session").
  11. - **flush\_context** – Internal [`UOWTransaction`]($346e0d9b88264a1f.md#sqlalchemy.orm.UOWTransaction "sqlalchemy.orm.UOWTransaction") object which handles the details of the flush.
  12. See also
  13. [`SessionEvents.before_flush()`](#sqlalchemy.orm.SessionEvents.before_flush "sqlalchemy.orm.SessionEvents.before_flush")
  14. [`SessionEvents.after_flush_postexec()`](#sqlalchemy.orm.SessionEvents.after_flush_postexec "sqlalchemy.orm.SessionEvents.after_flush_postexec")
  15. [Persistence Events]($10c3a07c3c01c2c3.md#session-persistence-events)
  • method sqlalchemy.orm.SessionEvents.after_flush_postexec(session, flush_context)

    Execute after flush has completed, and after the post-exec state occurs.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeSessionOrFactory, 'after_flush_postexec')
  2. def receive_after_flush_postexec(session, flush_context):
  3. "listen for the 'after_flush_postexec' event"
  4. # ... (event handling logic) ...
  5. ```
  6. This will be when the ‘new’, ‘dirty’, and ‘deleted’ lists are in their final state. An actual commit() may or may not have occurred, depending on whether or not the flush started its own transaction or participated in a larger transaction.
  7. - Parameters
  8. - **session** – The target [`Session`]($2d92bd546622cf54.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session").
  9. - **flush\_context** – Internal [`UOWTransaction`]($346e0d9b88264a1f.md#sqlalchemy.orm.UOWTransaction "sqlalchemy.orm.UOWTransaction") object which handles the details of the flush.
  10. See also
  11. [`SessionEvents.before_flush()`](#sqlalchemy.orm.SessionEvents.before_flush "sqlalchemy.orm.SessionEvents.before_flush")
  12. [`SessionEvents.after_flush()`](#sqlalchemy.orm.SessionEvents.after_flush "sqlalchemy.orm.SessionEvents.after_flush")
  13. [Persistence Events]($10c3a07c3c01c2c3.md#session-persistence-events)
  • method sqlalchemy.orm.SessionEvents.after_rollback(session)

    Execute after a real DBAPI rollback has occurred.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeSessionOrFactory, 'after_rollback')
  2. def receive_after_rollback(session):
  3. "listen for the 'after_rollback' event"
  4. # ... (event handling logic) ...
  5. ```
  6. Note that this event only fires when the *actual* rollback against the database occurs - it does *not* fire each time the [`Session.rollback()`]($2d92bd546622cf54.md#sqlalchemy.orm.Session.rollback "sqlalchemy.orm.Session.rollback") method is called, if the underlying DBAPI transaction has already been rolled back. In many cases, the [`Session`]($2d92bd546622cf54.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session") will not be in an “active” state during this event, as the current transaction is not valid. To acquire a [`Session`]($2d92bd546622cf54.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session") which is active after the outermost rollback has proceeded, use the [`SessionEvents.after_soft_rollback()`](#sqlalchemy.orm.SessionEvents.after_soft_rollback "sqlalchemy.orm.SessionEvents.after_soft_rollback") event, checking the [`Session.is_active`]($2d92bd546622cf54.md#sqlalchemy.orm.Session.is_active "sqlalchemy.orm.Session.is_active") flag.
  7. - Parameters
  8. **session** – The target [`Session`]($2d92bd546622cf54.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session").
  • method sqlalchemy.orm.SessionEvents.after_soft_rollback(session, previous_transaction)

    Execute after any rollback has occurred, including “soft” rollbacks that don’t actually emit at the DBAPI level.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeSessionOrFactory, 'after_soft_rollback')
  2. def receive_after_soft_rollback(session, previous_transaction):
  3. "listen for the 'after_soft_rollback' event"
  4. # ... (event handling logic) ...
  5. ```
  6. This corresponds to both nested and outer rollbacks, i.e. the innermost rollback that calls the DBAPI’s rollback() method, as well as the enclosing rollback calls that only pop themselves from the transaction stack.
  7. The given [`Session`]($2d92bd546622cf54.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session") can be used to invoke SQL and [`Session.query()`]($2d92bd546622cf54.md#sqlalchemy.orm.Session.query "sqlalchemy.orm.Session.query") operations after an outermost rollback by first checking the [`Session.is_active`]($2d92bd546622cf54.md#sqlalchemy.orm.Session.is_active "sqlalchemy.orm.Session.is_active") flag:
  8. ```
  9. @event.listens_for(Session, "after_soft_rollback")
  10. def do_something(session, previous_transaction):
  11. if session.is_active:
  12. session.execute("select * from some_table")
  13. ```
  14. - Parameters
  15. - **session** – The target [`Session`]($2d92bd546622cf54.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session").
  16. - **previous\_transaction** – The [`SessionTransaction`]($2d92bd546622cf54.md#sqlalchemy.orm.SessionTransaction "sqlalchemy.orm.SessionTransaction") transactional marker object which was just closed. The current [`SessionTransaction`]($2d92bd546622cf54.md#sqlalchemy.orm.SessionTransaction "sqlalchemy.orm.SessionTransaction") for the given [`Session`]($2d92bd546622cf54.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session") is available via the [`Session.transaction`]($2d92bd546622cf54.md#sqlalchemy.orm.Session.transaction "sqlalchemy.orm.Session.transaction") attribute.
  1. @event.listens_for(SomeSessionOrFactory, 'after_transaction_create')
  2. def receive_after_transaction_create(session, transaction):
  3. "listen for the 'after_transaction_create' event"
  4. # ... (event handling logic) ...
  5. ```
  6. This event differs from [`SessionEvents.after_begin()`](#sqlalchemy.orm.SessionEvents.after_begin "sqlalchemy.orm.SessionEvents.after_begin") in that it occurs for each [`SessionTransaction`]($2d92bd546622cf54.md#sqlalchemy.orm.SessionTransaction "sqlalchemy.orm.SessionTransaction") overall, as opposed to when transactions are begun on individual database connections. It is also invoked for nested transactions and subtransactions, and is always matched by a corresponding [`SessionEvents.after_transaction_end()`](#sqlalchemy.orm.SessionEvents.after_transaction_end "sqlalchemy.orm.SessionEvents.after_transaction_end") event (assuming normal operation of the [`Session`]($2d92bd546622cf54.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session")).
  7. - Parameters
  8. - **session** – the target [`Session`]($2d92bd546622cf54.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session").
  9. - **transaction** –
  10. the target [`SessionTransaction`]($2d92bd546622cf54.md#sqlalchemy.orm.SessionTransaction "sqlalchemy.orm.SessionTransaction").
  11. To detect if this is the outermost [`SessionTransaction`]($2d92bd546622cf54.md#sqlalchemy.orm.SessionTransaction "sqlalchemy.orm.SessionTransaction"), as opposed to a “subtransaction” or a SAVEPOINT, test that the [`SessionTransaction.parent`]($2d92bd546622cf54.md#sqlalchemy.orm.SessionTransaction.parent "sqlalchemy.orm.SessionTransaction.parent") attribute is `None`:
  12. ```
  13. @event.listens_for(session, "after_transaction_create")
  14. def after_transaction_create(session, transaction):
  15. if transaction.parent is None:
  16. # work with top-level transaction
  17. ```
  18. To detect if the [`SessionTransaction`]($2d92bd546622cf54.md#sqlalchemy.orm.SessionTransaction "sqlalchemy.orm.SessionTransaction") is a SAVEPOINT, use the [`SessionTransaction.nested`]($2d92bd546622cf54.md#sqlalchemy.orm.SessionTransaction.nested "sqlalchemy.orm.SessionTransaction.nested") attribute:
  19. ```
  20. @event.listens_for(session, "after_transaction_create")
  21. def after_transaction_create(session, transaction):
  22. if transaction.nested:
  23. # work with SAVEPOINT transaction
  24. ```
  25. See also
  26. [`SessionTransaction`]($2d92bd546622cf54.md#sqlalchemy.orm.SessionTransaction "sqlalchemy.orm.SessionTransaction")
  27. [`SessionEvents.after_transaction_end()`](#sqlalchemy.orm.SessionEvents.after_transaction_end "sqlalchemy.orm.SessionEvents.after_transaction_end")
  1. @event.listens_for(SomeSessionOrFactory, 'after_transaction_end')
  2. def receive_after_transaction_end(session, transaction):
  3. "listen for the 'after_transaction_end' event"
  4. # ... (event handling logic) ...
  5. ```
  6. This event differs from [`SessionEvents.after_commit()`](#sqlalchemy.orm.SessionEvents.after_commit "sqlalchemy.orm.SessionEvents.after_commit") in that it corresponds to all [`SessionTransaction`]($2d92bd546622cf54.md#sqlalchemy.orm.SessionTransaction "sqlalchemy.orm.SessionTransaction") objects in use, including those for nested transactions and subtransactions, and is always matched by a corresponding [`SessionEvents.after_transaction_create()`](#sqlalchemy.orm.SessionEvents.after_transaction_create "sqlalchemy.orm.SessionEvents.after_transaction_create") event.
  7. - Parameters
  8. - **session** – the target [`Session`]($2d92bd546622cf54.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session").
  9. - **transaction** –
  10. the target [`SessionTransaction`]($2d92bd546622cf54.md#sqlalchemy.orm.SessionTransaction "sqlalchemy.orm.SessionTransaction").
  11. To detect if this is the outermost [`SessionTransaction`]($2d92bd546622cf54.md#sqlalchemy.orm.SessionTransaction "sqlalchemy.orm.SessionTransaction"), as opposed to a “subtransaction” or a SAVEPOINT, test that the [`SessionTransaction.parent`]($2d92bd546622cf54.md#sqlalchemy.orm.SessionTransaction.parent "sqlalchemy.orm.SessionTransaction.parent") attribute is `None`:
  12. ```
  13. @event.listens_for(session, "after_transaction_create")
  14. def after_transaction_end(session, transaction):
  15. if transaction.parent is None:
  16. # work with top-level transaction
  17. ```
  18. To detect if the [`SessionTransaction`]($2d92bd546622cf54.md#sqlalchemy.orm.SessionTransaction "sqlalchemy.orm.SessionTransaction") is a SAVEPOINT, use the [`SessionTransaction.nested`]($2d92bd546622cf54.md#sqlalchemy.orm.SessionTransaction.nested "sqlalchemy.orm.SessionTransaction.nested") attribute:
  19. ```
  20. @event.listens_for(session, "after_transaction_create")
  21. def after_transaction_end(session, transaction):
  22. if transaction.nested:
  23. # work with SAVEPOINT transaction
  24. ```
  25. See also
  26. [`SessionTransaction`]($2d92bd546622cf54.md#sqlalchemy.orm.SessionTransaction "sqlalchemy.orm.SessionTransaction")
  27. [`SessionEvents.after_transaction_create()`](#sqlalchemy.orm.SessionEvents.after_transaction_create "sqlalchemy.orm.SessionEvents.after_transaction_create")
  • method sqlalchemy.orm.SessionEvents.before_attach(session, instance)

    Execute before an instance is attached to a session.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeSessionOrFactory, 'before_attach')
  2. def receive_before_attach(session, instance):
  3. "listen for the 'before_attach' event"
  4. # ... (event handling logic) ...
  5. ```
  6. This is called before an add, delete or merge causes the object to be part of the session.
  7. See also
  8. [`SessionEvents.after_attach()`](#sqlalchemy.orm.SessionEvents.after_attach "sqlalchemy.orm.SessionEvents.after_attach")
  9. [Object Lifecycle Events]($10c3a07c3c01c2c3.md#session-lifecycle-events)
  • method sqlalchemy.orm.SessionEvents.before_commit(session)

    Execute before commit is called.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeSessionOrFactory, 'before_commit')
  2. def receive_before_commit(session):
  3. "listen for the 'before_commit' event"
  4. # ... (event handling logic) ...
  5. ```
  6. Note
  7. The [`SessionEvents.before_commit()`](#sqlalchemy.orm.SessionEvents.before_commit "sqlalchemy.orm.SessionEvents.before_commit") hook is *not* per-flush, that is, the [`Session`]($2d92bd546622cf54.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session") can emit SQL to the database many times within the scope of a transaction. For interception of these events, use the [`SessionEvents.before_flush()`](#sqlalchemy.orm.SessionEvents.before_flush "sqlalchemy.orm.SessionEvents.before_flush"), [`SessionEvents.after_flush()`](#sqlalchemy.orm.SessionEvents.after_flush "sqlalchemy.orm.SessionEvents.after_flush"), or [`SessionEvents.after_flush_postexec()`](#sqlalchemy.orm.SessionEvents.after_flush_postexec "sqlalchemy.orm.SessionEvents.after_flush_postexec") events.
  8. - Parameters
  9. **session** – The target [`Session`]($2d92bd546622cf54.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session").
  10. See also
  11. [`SessionEvents.after_commit()`](#sqlalchemy.orm.SessionEvents.after_commit "sqlalchemy.orm.SessionEvents.after_commit")
  12. [`SessionEvents.after_begin()`](#sqlalchemy.orm.SessionEvents.after_begin "sqlalchemy.orm.SessionEvents.after_begin")
  13. [`SessionEvents.after_transaction_create()`](#sqlalchemy.orm.SessionEvents.after_transaction_create "sqlalchemy.orm.SessionEvents.after_transaction_create")
  14. [`SessionEvents.after_transaction_end()`](#sqlalchemy.orm.SessionEvents.after_transaction_end "sqlalchemy.orm.SessionEvents.after_transaction_end")
  • method sqlalchemy.orm.SessionEvents.before_flush(session, flush_context, instances)

    Execute before flush process has started.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeSessionOrFactory, 'before_flush')
  2. def receive_before_flush(session, flush_context, instances):
  3. "listen for the 'before_flush' event"
  4. # ... (event handling logic) ...
  5. ```
  6. - Parameters
  7. - **session** – The target [`Session`]($2d92bd546622cf54.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session").
  8. - **flush\_context** – Internal [`UOWTransaction`]($346e0d9b88264a1f.md#sqlalchemy.orm.UOWTransaction "sqlalchemy.orm.UOWTransaction") object which handles the details of the flush.
  9. - **instances** – Usually `None`, this is the collection of objects which can be passed to the [`Session.flush()`]($2d92bd546622cf54.md#sqlalchemy.orm.Session.flush "sqlalchemy.orm.Session.flush") method (note this usage is deprecated).
  10. See also
  11. [`SessionEvents.after_flush()`](#sqlalchemy.orm.SessionEvents.after_flush "sqlalchemy.orm.SessionEvents.after_flush")
  12. [`SessionEvents.after_flush_postexec()`](#sqlalchemy.orm.SessionEvents.after_flush_postexec "sqlalchemy.orm.SessionEvents.after_flush_postexec")
  13. [Persistence Events]($10c3a07c3c01c2c3.md#session-persistence-events)
  • method sqlalchemy.orm.SessionEvents.deleted_to_detached(session, instance)

    Intercept the “deleted to detached” transition for a specific object.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeSessionOrFactory, 'deleted_to_detached')
  2. def receive_deleted_to_detached(session, instance):
  3. "listen for the 'deleted_to_detached' event"
  4. # ... (event handling logic) ...
  5. ```
  6. This event is invoked when a deleted object is evicted from the session. The typical case when this occurs is when the transaction for a [`Session`]($2d92bd546622cf54.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session") in which the object was deleted is committed; the object moves from the deleted state to the detached state.
  7. It is also invoked for objects that were deleted in a flush when the [`Session.expunge_all()`]($2d92bd546622cf54.md#sqlalchemy.orm.Session.expunge_all "sqlalchemy.orm.Session.expunge_all") or [`Session.close()`]($2d92bd546622cf54.md#sqlalchemy.orm.Session.close "sqlalchemy.orm.Session.close") events are called, as well as if the object is individually expunged from its deleted state via [`Session.expunge()`]($2d92bd546622cf54.md#sqlalchemy.orm.Session.expunge "sqlalchemy.orm.Session.expunge").
  8. New in version 1.1.
  9. See also
  10. [Object Lifecycle Events]($10c3a07c3c01c2c3.md#session-lifecycle-events)
  • method sqlalchemy.orm.SessionEvents.deleted_to_persistent(session, instance)

    Intercept the “deleted to persistent” transition for a specific object.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeSessionOrFactory, 'deleted_to_persistent')
  2. def receive_deleted_to_persistent(session, instance):
  3. "listen for the 'deleted_to_persistent' event"
  4. # ... (event handling logic) ...
  5. ```
  6. This transition occurs only when an object that’s been deleted successfully in a flush is restored due to a call to [`Session.rollback()`]($2d92bd546622cf54.md#sqlalchemy.orm.Session.rollback "sqlalchemy.orm.Session.rollback"). The event is not called under any other circumstances.
  7. New in version 1.1.
  8. See also
  9. [Object Lifecycle Events]($10c3a07c3c01c2c3.md#session-lifecycle-events)
  • method sqlalchemy.orm.SessionEvents.detached_to_persistent(session, instance)

    Intercept the “detached to persistent” transition for a specific object.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeSessionOrFactory, 'detached_to_persistent')
  2. def receive_detached_to_persistent(session, instance):
  3. "listen for the 'detached_to_persistent' event"
  4. # ... (event handling logic) ...
  5. ```
  6. This event is a specialization of the [`SessionEvents.after_attach()`](#sqlalchemy.orm.SessionEvents.after_attach "sqlalchemy.orm.SessionEvents.after_attach") event which is only invoked for this specific transition. It is invoked typically during the [`Session.add()`]($2d92bd546622cf54.md#sqlalchemy.orm.Session.add "sqlalchemy.orm.Session.add") call, as well as during the [`Session.delete()`]($2d92bd546622cf54.md#sqlalchemy.orm.Session.delete "sqlalchemy.orm.Session.delete") call if the object was not previously associated with the [`Session`]($2d92bd546622cf54.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session") (note that an object marked as “deleted” remains in the “persistent” state until the flush proceeds).
  7. Note
  8. If the object becomes persistent as part of a call to [`Session.delete()`]($2d92bd546622cf54.md#sqlalchemy.orm.Session.delete "sqlalchemy.orm.Session.delete"), the object is **not** yet marked as deleted when this event is called. To detect deleted objects, check the `deleted` flag sent to the [`SessionEvents.persistent_to_detached()`](#sqlalchemy.orm.SessionEvents.persistent_to_detached "sqlalchemy.orm.SessionEvents.persistent_to_detached") to event after the flush proceeds, or check the [`Session.deleted`]($2d92bd546622cf54.md#sqlalchemy.orm.Session.deleted "sqlalchemy.orm.Session.deleted") collection within the [`SessionEvents.before_flush()`](#sqlalchemy.orm.SessionEvents.before_flush "sqlalchemy.orm.SessionEvents.before_flush") event if deleted objects need to be intercepted before the flush.
  9. - Parameters
  10. - **session** – target [`Session`]($2d92bd546622cf54.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session")
  11. - **instance** – the ORM-mapped instance being operated upon.
  12. New in version 1.1.
  13. See also
  14. [Object Lifecycle Events]($10c3a07c3c01c2c3.md#session-lifecycle-events)
  • method sqlalchemy.orm.SessionEvents.do_orm_execute(orm_execute_state)

    Intercept statement executions that occur in terms of a Session.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeSessionOrFactory, 'do_orm_execute')
  2. def receive_do_orm_execute(orm_execute_state):
  3. "listen for the 'do_orm_execute' event"
  4. # ... (event handling logic) ...
  5. ```
  6. This event is invoked for all top-level SQL statements invoked from the [`Session.execute()`]($2d92bd546622cf54.md#sqlalchemy.orm.Session.execute "sqlalchemy.orm.Session.execute") method. As of SQLAlchemy 1.4, all ORM queries emitted on behalf of a [`Session`]($2d92bd546622cf54.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session") will flow through this method, so this event hook provides the single point at which ORM queries of all types may be intercepted before they are invoked, and additionally to replace their execution with a different process.
  7. This event is a `do_` event, meaning it has the capability to replace the operation that the [`Session.execute()`]($2d92bd546622cf54.md#sqlalchemy.orm.Session.execute "sqlalchemy.orm.Session.execute") method normally performs. The intended use for this includes sharding and result-caching schemes which may seek to invoke the same statement across multiple database connections, returning a result that is merged from each of them, or which don’t invoke the statement at all, instead returning data from a cache.
  8. The hook intends to replace the use of the `Query._execute_and_instances` method that could be subclassed prior to SQLAlchemy 1.4.
  9. - Parameters
  10. **orm\_execute\_state** – an instance of [`ORMExecuteState`]($2d92bd546622cf54.md#sqlalchemy.orm.ORMExecuteState "sqlalchemy.orm.ORMExecuteState") which contains all information about the current execution, as well as helper functions used to derive other commonly required information. See that object for details.
  11. See also
  12. [Execute Events]($10c3a07c3c01c2c3.md#session-execute-events) - top level documentation on how to use [`SessionEvents.do_orm_execute()`](#sqlalchemy.orm.SessionEvents.do_orm_execute "sqlalchemy.orm.SessionEvents.do_orm_execute")
  13. [`ORMExecuteState`]($2d92bd546622cf54.md#sqlalchemy.orm.ORMExecuteState "sqlalchemy.orm.ORMExecuteState") - the object passed to the [`SessionEvents.do_orm_execute()`](#sqlalchemy.orm.SessionEvents.do_orm_execute "sqlalchemy.orm.SessionEvents.do_orm_execute") event which contains all information about the statement to be invoked. It also provides an interface to extend the current statement, options, and parameters as well as an option that allows programmatic invocation of the statement at any point.
  14. [ORM Query Events]($2c0b4d5f30e4919a.md#examples-session-orm-events) - includes examples of using [`SessionEvents.do_orm_execute()`](#sqlalchemy.orm.SessionEvents.do_orm_execute "sqlalchemy.orm.SessionEvents.do_orm_execute")
  15. [Dogpile Caching]($2c0b4d5f30e4919a.md#examples-caching) - an example of how to integrate Dogpile caching with the ORM [`Session`]($2d92bd546622cf54.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session") making use of the [`SessionEvents.do_orm_execute()`](#sqlalchemy.orm.SessionEvents.do_orm_execute "sqlalchemy.orm.SessionEvents.do_orm_execute") event hook.
  16. [Horizontal Sharding]($2c0b4d5f30e4919a.md#examples-sharding) - the Horizontal Sharding example / extension relies upon the [`SessionEvents.do_orm_execute()`](#sqlalchemy.orm.SessionEvents.do_orm_execute "sqlalchemy.orm.SessionEvents.do_orm_execute") event hook to invoke a SQL statement on multiple backends and return a merged result.
  17. New in version 1.4.
  • method sqlalchemy.orm.SessionEvents.loaded_as_persistent(session, instance)

    Intercept the “loaded as persistent” transition for a specific object.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeSessionOrFactory, 'loaded_as_persistent')
  2. def receive_loaded_as_persistent(session, instance):
  3. "listen for the 'loaded_as_persistent' event"
  4. # ... (event handling logic) ...
  5. ```
  6. This event is invoked within the ORM loading process, and is invoked very similarly to the [`InstanceEvents.load()`](#sqlalchemy.orm.InstanceEvents.load "sqlalchemy.orm.InstanceEvents.load") event. However, the event here is linkable to a [`Session`]($2d92bd546622cf54.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session") class or instance, rather than to a mapper or class hierarchy, and integrates with the other session lifecycle events smoothly. The object is guaranteed to be present in the session’s identity map when this event is called.
  7. Note
  8. This event is invoked within the loader process before eager loaders may have been completed, and the object’s state may not be complete. Additionally, invoking row-level refresh operations on the object will place the object into a new loader context, interfering with the existing load context. See the note on [`InstanceEvents.load()`](#sqlalchemy.orm.InstanceEvents.load "sqlalchemy.orm.InstanceEvents.load") for background on making use of the [`SessionEvents.restore_load_context`](#sqlalchemy.orm.SessionEvents.params.restore_load_context "sqlalchemy.orm.SessionEvents") parameter, which works in the same manner as that of [`InstanceEvents.restore_load_context`](#sqlalchemy.orm.InstanceEvents.params.restore_load_context "sqlalchemy.orm.InstanceEvents"), in order to resolve this scenario.
  9. - Parameters
  10. - **session** – target [`Session`]($2d92bd546622cf54.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session")
  11. - **instance** – the ORM-mapped instance being operated upon.
  12. New in version 1.1.
  13. See also
  14. [Object Lifecycle Events]($10c3a07c3c01c2c3.md#session-lifecycle-events)
  • method sqlalchemy.orm.SessionEvents.pending_to_persistent(session, instance)

    Intercept the “pending to persistent”” transition for a specific object.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeSessionOrFactory, 'pending_to_persistent')
  2. def receive_pending_to_persistent(session, instance):
  3. "listen for the 'pending_to_persistent' event"
  4. # ... (event handling logic) ...
  5. ```
  6. This event is invoked within the flush process, and is similar to scanning the [`Session.new`]($2d92bd546622cf54.md#sqlalchemy.orm.Session.new "sqlalchemy.orm.Session.new") collection within the [`SessionEvents.after_flush()`](#sqlalchemy.orm.SessionEvents.after_flush "sqlalchemy.orm.SessionEvents.after_flush") event. However, in this case the object has already been moved to the persistent state when the event is called.
  7. - Parameters
  8. - **session** – target [`Session`]($2d92bd546622cf54.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session")
  9. - **instance** – the ORM-mapped instance being operated upon.
  10. New in version 1.1.
  11. See also
  12. [Object Lifecycle Events]($10c3a07c3c01c2c3.md#session-lifecycle-events)
  • method sqlalchemy.orm.SessionEvents.pending_to_transient(session, instance)

    Intercept the “pending to transient” transition for a specific object.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeSessionOrFactory, 'pending_to_transient')
  2. def receive_pending_to_transient(session, instance):
  3. "listen for the 'pending_to_transient' event"
  4. # ... (event handling logic) ...
  5. ```
  6. This less common transition occurs when an pending object that has not been flushed is evicted from the session; this can occur when the [`Session.rollback()`]($2d92bd546622cf54.md#sqlalchemy.orm.Session.rollback "sqlalchemy.orm.Session.rollback") method rolls back the transaction, or when the [`Session.expunge()`]($2d92bd546622cf54.md#sqlalchemy.orm.Session.expunge "sqlalchemy.orm.Session.expunge") method is used.
  7. - Parameters
  8. - **session** – target [`Session`]($2d92bd546622cf54.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session")
  9. - **instance** – the ORM-mapped instance being operated upon.
  10. New in version 1.1.
  11. See also
  12. [Object Lifecycle Events]($10c3a07c3c01c2c3.md#session-lifecycle-events)
  • method sqlalchemy.orm.SessionEvents.persistent_to_deleted(session, instance)

    Intercept the “persistent to deleted” transition for a specific object.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeSessionOrFactory, 'persistent_to_deleted')
  2. def receive_persistent_to_deleted(session, instance):
  3. "listen for the 'persistent_to_deleted' event"
  4. # ... (event handling logic) ...
  5. ```
  6. This event is invoked when a persistent object’s identity is deleted from the database within a flush, however the object still remains associated with the [`Session`]($2d92bd546622cf54.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session") until the transaction completes.
  7. If the transaction is rolled back, the object moves again to the persistent state, and the [`SessionEvents.deleted_to_persistent()`](#sqlalchemy.orm.SessionEvents.deleted_to_persistent "sqlalchemy.orm.SessionEvents.deleted_to_persistent") event is called. If the transaction is committed, the object becomes detached, which will emit the [`SessionEvents.deleted_to_detached()`](#sqlalchemy.orm.SessionEvents.deleted_to_detached "sqlalchemy.orm.SessionEvents.deleted_to_detached") event.
  8. Note that while the [`Session.delete()`]($2d92bd546622cf54.md#sqlalchemy.orm.Session.delete "sqlalchemy.orm.Session.delete") method is the primary public interface to mark an object as deleted, many objects get deleted due to cascade rules, which are not always determined until flush time. Therefore, there’s no way to catch every object that will be deleted until the flush has proceeded. the [`SessionEvents.persistent_to_deleted()`](#sqlalchemy.orm.SessionEvents.persistent_to_deleted "sqlalchemy.orm.SessionEvents.persistent_to_deleted") event is therefore invoked at the end of a flush.
  9. New in version 1.1.
  10. See also
  11. [Object Lifecycle Events]($10c3a07c3c01c2c3.md#session-lifecycle-events)
  • method sqlalchemy.orm.SessionEvents.persistent_to_detached(session, instance)

    Intercept the “persistent to detached” transition for a specific object.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeSessionOrFactory, 'persistent_to_detached')
  2. def receive_persistent_to_detached(session, instance):
  3. "listen for the 'persistent_to_detached' event"
  4. # ... (event handling logic) ...
  5. ```
  6. This event is invoked when a persistent object is evicted from the session. There are many conditions that cause this to happen, including:
  7. - using a method such as [`Session.expunge()`]($2d92bd546622cf54.md#sqlalchemy.orm.Session.expunge "sqlalchemy.orm.Session.expunge") or [`Session.close()`]($2d92bd546622cf54.md#sqlalchemy.orm.Session.close "sqlalchemy.orm.Session.close")
  8. - Calling the [`Session.rollback()`]($2d92bd546622cf54.md#sqlalchemy.orm.Session.rollback "sqlalchemy.orm.Session.rollback") method, when the object was part of an INSERT statement for that session’s transaction
  9. - Parameters
  10. - **session** – target [`Session`]($2d92bd546622cf54.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session")
  11. - **instance** – the ORM-mapped instance being operated upon.
  12. - **deleted** – boolean. If True, indicates this object moved to the detached state because it was marked as deleted and flushed.
  13. New in version 1.1.
  14. See also
  15. [Object Lifecycle Events]($10c3a07c3c01c2c3.md#session-lifecycle-events)
  • method sqlalchemy.orm.SessionEvents.persistent_to_transient(session, instance)

    Intercept the “persistent to transient” transition for a specific object.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeSessionOrFactory, 'persistent_to_transient')
  2. def receive_persistent_to_transient(session, instance):
  3. "listen for the 'persistent_to_transient' event"
  4. # ... (event handling logic) ...
  5. ```
  6. This less common transition occurs when an pending object that has has been flushed is evicted from the session; this can occur when the [`Session.rollback()`]($2d92bd546622cf54.md#sqlalchemy.orm.Session.rollback "sqlalchemy.orm.Session.rollback") method rolls back the transaction.
  7. - Parameters
  8. - **session** – target [`Session`]($2d92bd546622cf54.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session")
  9. - **instance** – the ORM-mapped instance being operated upon.
  10. New in version 1.1.
  11. See also
  12. [Object Lifecycle Events]($10c3a07c3c01c2c3.md#session-lifecycle-events)
  • method sqlalchemy.orm.SessionEvents.transient_to_pending(session, instance)

    Intercept the “transient to pending” transition for a specific object.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeSessionOrFactory, 'transient_to_pending')
  2. def receive_transient_to_pending(session, instance):
  3. "listen for the 'transient_to_pending' event"
  4. # ... (event handling logic) ...
  5. ```
  6. This event is a specialization of the [`SessionEvents.after_attach()`](#sqlalchemy.orm.SessionEvents.after_attach "sqlalchemy.orm.SessionEvents.after_attach") event which is only invoked for this specific transition. It is invoked typically during the [`Session.add()`]($2d92bd546622cf54.md#sqlalchemy.orm.Session.add "sqlalchemy.orm.Session.add") call.
  7. - Parameters
  8. - **session** – target [`Session`]($2d92bd546622cf54.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session")
  9. - **instance** – the ORM-mapped instance being operated upon.
  10. New in version 1.1.
  11. See also
  12. [Object Lifecycle Events]($10c3a07c3c01c2c3.md#session-lifecycle-events)

Mapper Events

Mapper event hooks encompass things that happen as related to individual or multiple Mapper objects, which are the central configurational object that maps a user-defined class to a Table object. Types of things which occur at the Mapper level include:

Object NameDescription

MapperEvents

Define events specific to mappings.

class sqlalchemy.orm.``MapperEvents

Define events specific to mappings.

e.g.:

  1. from sqlalchemy import event
  2. def my_before_insert_listener(mapper, connection, target):
  3. # execute a stored procedure upon INSERT,
  4. # apply the value to the row to be inserted
  5. target.calculated_value = connection.execute(
  6. text("select my_special_function(%d)" % target.special_number)
  7. ).scalar()
  8. # associate the listener function with SomeClass,
  9. # to execute during the "before_insert" hook
  10. event.listen(
  11. SomeClass, 'before_insert', my_before_insert_listener)

Available targets include:

  • mapped classes

  • unmapped superclasses of mapped or to-be-mapped classes (using the propagate=True flag)

  • Mapper objects

  • the Mapper class itself and the mapper() function indicate listening for all mappers.

Mapper events provide hooks into critical sections of the mapper, including those related to object instrumentation, object loading, and object persistence. In particular, the persistence methods MapperEvents.before_insert(), and MapperEvents.before_update() are popular places to augment the state being persisted - however, these methods operate with several significant restrictions. The user is encouraged to evaluate the SessionEvents.before_flush() and SessionEvents.after_flush() methods as more flexible and user-friendly hooks in which to apply additional database state during a flush.

When using MapperEvents, several modifiers are available to the listen() function.

  • Parameters

    • propagate=False – When True, the event listener should be applied to all inheriting mappers and/or the mappers of inheriting classes, as well as any mapper which is the target of this listener.

    • raw=False – When True, the “target” argument passed to applicable event listener functions will be the instance’s InstanceState management object, rather than the mapped instance itself.

    • retval=False

      when True, the user-defined event function must have a return value, the purpose of which is either to control subsequent event propagation, or to otherwise alter the operation in progress by the mapper. Possible return values are:

      • sqlalchemy.orm.interfaces.EXT_CONTINUE - continue event processing normally.

      • sqlalchemy.orm.interfaces.EXT_STOP - cancel all subsequent event handlers in the chain.

      • other values - the return value specified by specific listeners.

Class signature

class sqlalchemy.orm.MapperEvents (sqlalchemy.event.Events)

  • method sqlalchemy.orm.MapperEvents.after_configured()

    Called after a series of mappers have been configured.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeClass, 'after_configured')
  2. def receive_after_configured():
  3. "listen for the 'after_configured' event"
  4. # ... (event handling logic) ...
  5. ```
  6. The [`MapperEvents.after_configured()`](#sqlalchemy.orm.MapperEvents.after_configured "sqlalchemy.orm.MapperEvents.after_configured") event is invoked each time the [`configure_mappers()`]($02c0a61f4d785504.md#sqlalchemy.orm.configure_mappers "sqlalchemy.orm.configure_mappers") function is invoked, after the function has completed its work. [`configure_mappers()`]($02c0a61f4d785504.md#sqlalchemy.orm.configure_mappers "sqlalchemy.orm.configure_mappers") is typically invoked automatically as mappings are first used, as well as each time new mappers have been made available and new mapper use is detected.
  7. Contrast this event to the [`MapperEvents.mapper_configured()`](#sqlalchemy.orm.MapperEvents.mapper_configured "sqlalchemy.orm.MapperEvents.mapper_configured") event, which is called on a per-mapper basis while the configuration operation proceeds; unlike that event, when this event is invoked, all cross-configurations (e.g. backrefs) will also have been made available for any mappers that were pending. Also contrast to [`MapperEvents.before_configured()`](#sqlalchemy.orm.MapperEvents.before_configured "sqlalchemy.orm.MapperEvents.before_configured"), which is invoked before the series of mappers has been configured.
  8. This event can **only** be applied to the [`Mapper`]($02c0a61f4d785504.md#sqlalchemy.orm.Mapper "sqlalchemy.orm.Mapper") class or [`mapper()`]($02c0a61f4d785504.md#sqlalchemy.orm.mapper "sqlalchemy.orm.mapper") function, and not to individual mappings or mapped classes. It is only invoked for all mappings as a whole:
  9. ```
  10. from sqlalchemy.orm import mapper
  11. @event.listens_for(mapper, "after_configured")
  12. def go():
  13. # ...
  14. ```
  15. Theoretically this event is called once per application, but is actually called any time new mappers have been affected by a [`configure_mappers()`]($02c0a61f4d785504.md#sqlalchemy.orm.configure_mappers "sqlalchemy.orm.configure_mappers") call. If new mappings are constructed after existing ones have already been used, this event will likely be called again. To ensure that a particular event is only called once and no further, the `once=True` argument (new in 0.9.4) can be applied:
  16. ```
  17. from sqlalchemy.orm import mapper
  18. @event.listens_for(mapper, "after_configured", once=True)
  19. def go():
  20. # ...
  21. ```
  22. See also
  23. [`MapperEvents.before_mapper_configured()`](#sqlalchemy.orm.MapperEvents.before_mapper_configured "sqlalchemy.orm.MapperEvents.before_mapper_configured")
  24. [`MapperEvents.mapper_configured()`](#sqlalchemy.orm.MapperEvents.mapper_configured "sqlalchemy.orm.MapperEvents.mapper_configured")
  25. [`MapperEvents.before_configured()`](#sqlalchemy.orm.MapperEvents.before_configured "sqlalchemy.orm.MapperEvents.before_configured")
  • method sqlalchemy.orm.MapperEvents.after_delete(mapper, connection, target)

    Receive an object instance after a DELETE statement has been emitted corresponding to that instance.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeClass, 'after_delete')
  2. def receive_after_delete(mapper, connection, target):
  3. "listen for the 'after_delete' event"
  4. # ... (event handling logic) ...
  5. ```
  6. This event is used to emit additional SQL statements on the given connection as well as to perform application specific bookkeeping related to a deletion event.
  7. The event is often called for a batch of objects of the same class after their DELETE statements have been emitted at once in a previous step.
  8. Warning
  9. Mapper-level flush events only allow **very limited operations**, on attributes local to the row being operated upon only, as well as allowing any SQL to be emitted on the given [`Connection`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection"). **Please read fully** the notes at [Mapper-level Events]($10c3a07c3c01c2c3.md#session-persistence-mapper) for guidelines on using these methods; generally, the [`SessionEvents.before_flush()`](#sqlalchemy.orm.SessionEvents.before_flush "sqlalchemy.orm.SessionEvents.before_flush") method should be preferred for general on-flush changes.
  10. - Parameters
  11. - **mapper** – the [`Mapper`]($02c0a61f4d785504.md#sqlalchemy.orm.Mapper "sqlalchemy.orm.Mapper") which is the target of this event.
  12. - **connection** – the [`Connection`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") being used to emit DELETE statements for this instance. This provides a handle into the current transaction on the target database specific to this instance.
  13. - **target** – the mapped instance being deleted. If the event is configured with `raw=True`, this will instead be the [`InstanceState`]($346e0d9b88264a1f.md#sqlalchemy.orm.InstanceState "sqlalchemy.orm.InstanceState") state-management object associated with the instance.
  14. Returns
  15. No return value is supported by this event.
  16. See also
  17. [Persistence Events]($10c3a07c3c01c2c3.md#session-persistence-events)
  • method sqlalchemy.orm.MapperEvents.after_insert(mapper, connection, target)

    Receive an object instance after an INSERT statement is emitted corresponding to that instance.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeClass, 'after_insert')
  2. def receive_after_insert(mapper, connection, target):
  3. "listen for the 'after_insert' event"
  4. # ... (event handling logic) ...
  5. ```
  6. This event is used to modify in-Python-only state on the instance after an INSERT occurs, as well as to emit additional SQL statements on the given connection.
  7. The event is often called for a batch of objects of the same class after their INSERT statements have been emitted at once in a previous step. In the extremely rare case that this is not desirable, the [`mapper()`]($02c0a61f4d785504.md#sqlalchemy.orm.mapper "sqlalchemy.orm.mapper") can be configured with `batch=False`, which will cause batches of instances to be broken up into individual (and more poorly performing) event->persist->event steps.
  8. Warning
  9. Mapper-level flush events only allow **very limited operations**, on attributes local to the row being operated upon only, as well as allowing any SQL to be emitted on the given [`Connection`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection"). **Please read fully** the notes at [Mapper-level Events]($10c3a07c3c01c2c3.md#session-persistence-mapper) for guidelines on using these methods; generally, the [`SessionEvents.before_flush()`](#sqlalchemy.orm.SessionEvents.before_flush "sqlalchemy.orm.SessionEvents.before_flush") method should be preferred for general on-flush changes.
  10. - Parameters
  11. - **mapper** – the [`Mapper`]($02c0a61f4d785504.md#sqlalchemy.orm.Mapper "sqlalchemy.orm.Mapper") which is the target of this event.
  12. - **connection** – the [`Connection`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") being used to emit INSERT statements for this instance. This provides a handle into the current transaction on the target database specific to this instance.
  13. - **target** – the mapped instance being persisted. If the event is configured with `raw=True`, this will instead be the [`InstanceState`]($346e0d9b88264a1f.md#sqlalchemy.orm.InstanceState "sqlalchemy.orm.InstanceState") state-management object associated with the instance.
  14. Returns
  15. No return value is supported by this event.
  16. See also
  17. [Persistence Events]($10c3a07c3c01c2c3.md#session-persistence-events)
  • method sqlalchemy.orm.MapperEvents.after_update(mapper, connection, target)

    Receive an object instance after an UPDATE statement is emitted corresponding to that instance.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeClass, 'after_update')
  2. def receive_after_update(mapper, connection, target):
  3. "listen for the 'after_update' event"
  4. # ... (event handling logic) ...
  5. ```
  6. This event is used to modify in-Python-only state on the instance after an UPDATE occurs, as well as to emit additional SQL statements on the given connection.
  7. This method is called for all instances that are marked as “dirty”, *even those which have no net changes to their column-based attributes*, and for which no UPDATE statement has proceeded. An object is marked as dirty when any of its column-based attributes have a “set attribute” operation called or when any of its collections are modified. If, at update time, no column-based attributes have any net changes, no UPDATE statement will be issued. This means that an instance being sent to [`MapperEvents.after_update()`](#sqlalchemy.orm.MapperEvents.after_update "sqlalchemy.orm.MapperEvents.after_update") is *not* a guarantee that an UPDATE statement has been issued.
  8. To detect if the column-based attributes on the object have net changes, and therefore resulted in an UPDATE statement, use `object_session(instance).is_modified(instance, include_collections=False)`.
  9. The event is often called for a batch of objects of the same class after their UPDATE statements have been emitted at once in a previous step. In the extremely rare case that this is not desirable, the [`mapper()`]($02c0a61f4d785504.md#sqlalchemy.orm.mapper "sqlalchemy.orm.mapper") can be configured with `batch=False`, which will cause batches of instances to be broken up into individual (and more poorly performing) event->persist->event steps.
  10. Warning
  11. Mapper-level flush events only allow **very limited operations**, on attributes local to the row being operated upon only, as well as allowing any SQL to be emitted on the given [`Connection`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection"). **Please read fully** the notes at [Mapper-level Events]($10c3a07c3c01c2c3.md#session-persistence-mapper) for guidelines on using these methods; generally, the [`SessionEvents.before_flush()`](#sqlalchemy.orm.SessionEvents.before_flush "sqlalchemy.orm.SessionEvents.before_flush") method should be preferred for general on-flush changes.
  12. - Parameters
  13. - **mapper** – the [`Mapper`]($02c0a61f4d785504.md#sqlalchemy.orm.Mapper "sqlalchemy.orm.Mapper") which is the target of this event.
  14. - **connection** – the [`Connection`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") being used to emit UPDATE statements for this instance. This provides a handle into the current transaction on the target database specific to this instance.
  15. - **target** – the mapped instance being persisted. If the event is configured with `raw=True`, this will instead be the [`InstanceState`]($346e0d9b88264a1f.md#sqlalchemy.orm.InstanceState "sqlalchemy.orm.InstanceState") state-management object associated with the instance.
  16. Returns
  17. No return value is supported by this event.
  18. See also
  19. [Persistence Events]($10c3a07c3c01c2c3.md#session-persistence-events)
  • method sqlalchemy.orm.MapperEvents.before_configured()

    Called before a series of mappers have been configured.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeClass, 'before_configured')
  2. def receive_before_configured():
  3. "listen for the 'before_configured' event"
  4. # ... (event handling logic) ...
  5. ```
  6. The [`MapperEvents.before_configured()`](#sqlalchemy.orm.MapperEvents.before_configured "sqlalchemy.orm.MapperEvents.before_configured") event is invoked each time the [`configure_mappers()`]($02c0a61f4d785504.md#sqlalchemy.orm.configure_mappers "sqlalchemy.orm.configure_mappers") function is invoked, before the function has done any of its work. [`configure_mappers()`]($02c0a61f4d785504.md#sqlalchemy.orm.configure_mappers "sqlalchemy.orm.configure_mappers") is typically invoked automatically as mappings are first used, as well as each time new mappers have been made available and new mapper use is detected.
  7. This event can **only** be applied to the [`Mapper`]($02c0a61f4d785504.md#sqlalchemy.orm.Mapper "sqlalchemy.orm.Mapper") class or [`mapper()`]($02c0a61f4d785504.md#sqlalchemy.orm.mapper "sqlalchemy.orm.mapper") function, and not to individual mappings or mapped classes. It is only invoked for all mappings as a whole:
  8. ```
  9. from sqlalchemy.orm import mapper
  10. @event.listens_for(mapper, "before_configured")
  11. def go():
  12. # ...
  13. ```
  14. Contrast this event to [`MapperEvents.after_configured()`](#sqlalchemy.orm.MapperEvents.after_configured "sqlalchemy.orm.MapperEvents.after_configured"), which is invoked after the series of mappers has been configured, as well as [`MapperEvents.before_mapper_configured()`](#sqlalchemy.orm.MapperEvents.before_mapper_configured "sqlalchemy.orm.MapperEvents.before_mapper_configured") and [`MapperEvents.mapper_configured()`](#sqlalchemy.orm.MapperEvents.mapper_configured "sqlalchemy.orm.MapperEvents.mapper_configured"), which are both invoked on a per-mapper basis.
  15. Theoretically this event is called once per application, but is actually called any time new mappers are to be affected by a [`configure_mappers()`]($02c0a61f4d785504.md#sqlalchemy.orm.configure_mappers "sqlalchemy.orm.configure_mappers") call. If new mappings are constructed after existing ones have already been used, this event will likely be called again. To ensure that a particular event is only called once and no further, the `once=True` argument (new in 0.9.4) can be applied:
  16. ```
  17. from sqlalchemy.orm import mapper
  18. @event.listens_for(mapper, "before_configured", once=True)
  19. def go():
  20. # ...
  21. ```
  22. New in version 0.9.3.
  23. See also
  24. [`MapperEvents.before_mapper_configured()`](#sqlalchemy.orm.MapperEvents.before_mapper_configured "sqlalchemy.orm.MapperEvents.before_mapper_configured")
  25. [`MapperEvents.mapper_configured()`](#sqlalchemy.orm.MapperEvents.mapper_configured "sqlalchemy.orm.MapperEvents.mapper_configured")
  26. [`MapperEvents.after_configured()`](#sqlalchemy.orm.MapperEvents.after_configured "sqlalchemy.orm.MapperEvents.after_configured")
  • method sqlalchemy.orm.MapperEvents.before_delete(mapper, connection, target)

    Receive an object instance before a DELETE statement is emitted corresponding to that instance.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeClass, 'before_delete')
  2. def receive_before_delete(mapper, connection, target):
  3. "listen for the 'before_delete' event"
  4. # ... (event handling logic) ...
  5. ```
  6. This event is used to emit additional SQL statements on the given connection as well as to perform application specific bookkeeping related to a deletion event.
  7. The event is often called for a batch of objects of the same class before their DELETE statements are emitted at once in a later step.
  8. Warning
  9. Mapper-level flush events only allow **very limited operations**, on attributes local to the row being operated upon only, as well as allowing any SQL to be emitted on the given [`Connection`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection"). **Please read fully** the notes at [Mapper-level Events]($10c3a07c3c01c2c3.md#session-persistence-mapper) for guidelines on using these methods; generally, the [`SessionEvents.before_flush()`](#sqlalchemy.orm.SessionEvents.before_flush "sqlalchemy.orm.SessionEvents.before_flush") method should be preferred for general on-flush changes.
  10. - Parameters
  11. - **mapper** – the [`Mapper`]($02c0a61f4d785504.md#sqlalchemy.orm.Mapper "sqlalchemy.orm.Mapper") which is the target of this event.
  12. - **connection** – the [`Connection`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") being used to emit DELETE statements for this instance. This provides a handle into the current transaction on the target database specific to this instance.
  13. - **target** – the mapped instance being deleted. If the event is configured with `raw=True`, this will instead be the [`InstanceState`]($346e0d9b88264a1f.md#sqlalchemy.orm.InstanceState "sqlalchemy.orm.InstanceState") state-management object associated with the instance.
  14. Returns
  15. No return value is supported by this event.
  16. See also
  17. [Persistence Events]($10c3a07c3c01c2c3.md#session-persistence-events)
  • method sqlalchemy.orm.MapperEvents.before_insert(mapper, connection, target)

    Receive an object instance before an INSERT statement is emitted corresponding to that instance.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeClass, 'before_insert')
  2. def receive_before_insert(mapper, connection, target):
  3. "listen for the 'before_insert' event"
  4. # ... (event handling logic) ...
  5. ```
  6. This event is used to modify local, non-object related attributes on the instance before an INSERT occurs, as well as to emit additional SQL statements on the given connection.
  7. The event is often called for a batch of objects of the same class before their INSERT statements are emitted at once in a later step. In the extremely rare case that this is not desirable, the [`mapper()`]($02c0a61f4d785504.md#sqlalchemy.orm.mapper "sqlalchemy.orm.mapper") can be configured with `batch=False`, which will cause batches of instances to be broken up into individual (and more poorly performing) event->persist->event steps.
  8. Warning
  9. Mapper-level flush events only allow **very limited operations**, on attributes local to the row being operated upon only, as well as allowing any SQL to be emitted on the given [`Connection`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection"). **Please read fully** the notes at [Mapper-level Events]($10c3a07c3c01c2c3.md#session-persistence-mapper) for guidelines on using these methods; generally, the [`SessionEvents.before_flush()`](#sqlalchemy.orm.SessionEvents.before_flush "sqlalchemy.orm.SessionEvents.before_flush") method should be preferred for general on-flush changes.
  10. - Parameters
  11. - **mapper** – the [`Mapper`]($02c0a61f4d785504.md#sqlalchemy.orm.Mapper "sqlalchemy.orm.Mapper") which is the target of this event.
  12. - **connection** – the [`Connection`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") being used to emit INSERT statements for this instance. This provides a handle into the current transaction on the target database specific to this instance.
  13. - **target** – the mapped instance being persisted. If the event is configured with `raw=True`, this will instead be the [`InstanceState`]($346e0d9b88264a1f.md#sqlalchemy.orm.InstanceState "sqlalchemy.orm.InstanceState") state-management object associated with the instance.
  14. Returns
  15. No return value is supported by this event.
  16. See also
  17. [Persistence Events]($10c3a07c3c01c2c3.md#session-persistence-events)
  • method sqlalchemy.orm.MapperEvents.before_mapper_configured(mapper, class_)

    Called right before a specific mapper is to be configured.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeClass, 'before_mapper_configured')
  2. def receive_before_mapper_configured(mapper, class_):
  3. "listen for the 'before_mapper_configured' event"
  4. # ... (event handling logic) ...
  5. ```
  6. This event is intended to allow a specific mapper to be skipped during the configure step, by returning the `interfaces.EXT_SKIP` symbol which indicates to the [`configure_mappers()`]($02c0a61f4d785504.md#sqlalchemy.orm.configure_mappers "sqlalchemy.orm.configure_mappers") call that this particular mapper (or hierarchy of mappers, if `propagate=True` is used) should be skipped in the current configuration run. When one or more mappers are skipped, the he “new mappers” flag will remain set, meaning the [`configure_mappers()`]($02c0a61f4d785504.md#sqlalchemy.orm.configure_mappers "sqlalchemy.orm.configure_mappers") function will continue to be called when mappers are used, to continue to try to configure all available mappers.
  7. In comparison to the other configure-level events, [`MapperEvents.before_configured()`](#sqlalchemy.orm.MapperEvents.before_configured "sqlalchemy.orm.MapperEvents.before_configured"), [`MapperEvents.after_configured()`](#sqlalchemy.orm.MapperEvents.after_configured "sqlalchemy.orm.MapperEvents.after_configured"), and [`MapperEvents.mapper_configured()`](#sqlalchemy.orm.MapperEvents.mapper_configured "sqlalchemy.orm.MapperEvents.mapper_configured"), the :meth;\`.MapperEvents.before\_mapper\_configured\` event provides for a meaningful return value when it is registered with the `retval=True` parameter.
  8. New in version 1.3.
  9. e.g.:
  10. ```
  11. from sqlalchemy.orm import EXT_SKIP
  12. Base = declarative_base()
  13. DontConfigureBase = declarative_base()
  14. @event.listens_for(
  15. DontConfigureBase,
  16. "before_mapper_configured", retval=True, propagate=True)
  17. def dont_configure(mapper, cls):
  18. return EXT_SKIP
  19. ```
  20. See also
  21. [`MapperEvents.before_configured()`](#sqlalchemy.orm.MapperEvents.before_configured "sqlalchemy.orm.MapperEvents.before_configured")
  22. [`MapperEvents.after_configured()`](#sqlalchemy.orm.MapperEvents.after_configured "sqlalchemy.orm.MapperEvents.after_configured")
  23. [`MapperEvents.mapper_configured()`](#sqlalchemy.orm.MapperEvents.mapper_configured "sqlalchemy.orm.MapperEvents.mapper_configured")
  • method sqlalchemy.orm.MapperEvents.before_update(mapper, connection, target)

    Receive an object instance before an UPDATE statement is emitted corresponding to that instance.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeClass, 'before_update')
  2. def receive_before_update(mapper, connection, target):
  3. "listen for the 'before_update' event"
  4. # ... (event handling logic) ...
  5. ```
  6. This event is used to modify local, non-object related attributes on the instance before an UPDATE occurs, as well as to emit additional SQL statements on the given connection.
  7. This method is called for all instances that are marked as “dirty”, *even those which have no net changes to their column-based attributes*. An object is marked as dirty when any of its column-based attributes have a “set attribute” operation called or when any of its collections are modified. If, at update time, no column-based attributes have any net changes, no UPDATE statement will be issued. This means that an instance being sent to [`MapperEvents.before_update()`](#sqlalchemy.orm.MapperEvents.before_update "sqlalchemy.orm.MapperEvents.before_update") is *not* a guarantee that an UPDATE statement will be issued, although you can affect the outcome here by modifying attributes so that a net change in value does exist.
  8. To detect if the column-based attributes on the object have net changes, and will therefore generate an UPDATE statement, use `object_session(instance).is_modified(instance, include_collections=False)`.
  9. The event is often called for a batch of objects of the same class before their UPDATE statements are emitted at once in a later step. In the extremely rare case that this is not desirable, the [`mapper()`]($02c0a61f4d785504.md#sqlalchemy.orm.mapper "sqlalchemy.orm.mapper") can be configured with `batch=False`, which will cause batches of instances to be broken up into individual (and more poorly performing) event->persist->event steps.
  10. Warning
  11. Mapper-level flush events only allow **very limited operations**, on attributes local to the row being operated upon only, as well as allowing any SQL to be emitted on the given [`Connection`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection"). **Please read fully** the notes at [Mapper-level Events]($10c3a07c3c01c2c3.md#session-persistence-mapper) for guidelines on using these methods; generally, the [`SessionEvents.before_flush()`](#sqlalchemy.orm.SessionEvents.before_flush "sqlalchemy.orm.SessionEvents.before_flush") method should be preferred for general on-flush changes.
  12. - Parameters
  13. - **mapper** – the [`Mapper`]($02c0a61f4d785504.md#sqlalchemy.orm.Mapper "sqlalchemy.orm.Mapper") which is the target of this event.
  14. - **connection** – the [`Connection`]($cd778e34cf5e4642.md#sqlalchemy.engine.Connection "sqlalchemy.engine.Connection") being used to emit UPDATE statements for this instance. This provides a handle into the current transaction on the target database specific to this instance.
  15. - **target** – the mapped instance being persisted. If the event is configured with `raw=True`, this will instead be the [`InstanceState`]($346e0d9b88264a1f.md#sqlalchemy.orm.InstanceState "sqlalchemy.orm.InstanceState") state-management object associated with the instance.
  16. Returns
  17. No return value is supported by this event.
  18. See also
  19. [Persistence Events]($10c3a07c3c01c2c3.md#session-persistence-events)
  • method sqlalchemy.orm.MapperEvents.instrument_class(mapper, class_)

    Receive a class when the mapper is first constructed, before instrumentation is applied to the mapped class.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeClass, 'instrument_class')
  2. def receive_instrument_class(mapper, class_):
  3. "listen for the 'instrument_class' event"
  4. # ... (event handling logic) ...
  5. ```
  6. This event is the earliest phase of mapper construction. Most attributes of the mapper are not yet initialized.
  7. This listener can either be applied to the [`Mapper`]($02c0a61f4d785504.md#sqlalchemy.orm.Mapper "sqlalchemy.orm.Mapper") class overall, or to any un-mapped class which serves as a base for classes that will be mapped (using the `propagate=True` flag):
  8. ```
  9. Base = declarative_base()
  10. @event.listens_for(Base, "instrument_class", propagate=True)
  11. def on_new_class(mapper, cls_):
  12. " ... "
  13. ```
  14. - Parameters
  15. - **mapper** – the [`Mapper`]($02c0a61f4d785504.md#sqlalchemy.orm.Mapper "sqlalchemy.orm.Mapper") which is the target of this event.
  16. - **class\_** – the mapped class.
  • method sqlalchemy.orm.MapperEvents.mapper_configured(mapper, class_)

    Called when a specific mapper has completed its own configuration within the scope of the configure_mappers() call.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeClass, 'mapper_configured')
  2. def receive_mapper_configured(mapper, class_):
  3. "listen for the 'mapper_configured' event"
  4. # ... (event handling logic) ...
  5. ```
  6. The [`MapperEvents.mapper_configured()`](#sqlalchemy.orm.MapperEvents.mapper_configured "sqlalchemy.orm.MapperEvents.mapper_configured") event is invoked for each mapper that is encountered when the [`configure_mappers()`]($02c0a61f4d785504.md#sqlalchemy.orm.configure_mappers "sqlalchemy.orm.configure_mappers") function proceeds through the current list of not-yet-configured mappers. [`configure_mappers()`]($02c0a61f4d785504.md#sqlalchemy.orm.configure_mappers "sqlalchemy.orm.configure_mappers") is typically invoked automatically as mappings are first used, as well as each time new mappers have been made available and new mapper use is detected.
  7. When the event is called, the mapper should be in its final state, but **not including backrefs** that may be invoked from other mappers; they might still be pending within the configuration operation. Bidirectional relationships that are instead configured via the [`relationship.back_populates`]($7c85a873b6a4b509.md#sqlalchemy.orm.relationship.params.back_populates "sqlalchemy.orm.relationship") argument *will* be fully available, since this style of relationship does not rely upon other possibly-not-configured mappers to know that they exist.
  8. For an event that is guaranteed to have **all** mappers ready to go including backrefs that are defined only on other mappings, use the [`MapperEvents.after_configured()`](#sqlalchemy.orm.MapperEvents.after_configured "sqlalchemy.orm.MapperEvents.after_configured") event; this event invokes only after all known mappings have been fully configured.
  9. The [`MapperEvents.mapper_configured()`](#sqlalchemy.orm.MapperEvents.mapper_configured "sqlalchemy.orm.MapperEvents.mapper_configured") event, unlike [`MapperEvents.before_configured()`](#sqlalchemy.orm.MapperEvents.before_configured "sqlalchemy.orm.MapperEvents.before_configured") or [`MapperEvents.after_configured()`](#sqlalchemy.orm.MapperEvents.after_configured "sqlalchemy.orm.MapperEvents.after_configured"), is called for each mapper/class individually, and the mapper is passed to the event itself. It also is called exactly once for a particular mapper. The event is therefore useful for configurational steps that benefit from being invoked just once on a specific mapper basis, which don’t require that “backref” configurations are necessarily ready yet.
  10. - Parameters
  11. - **mapper** – the [`Mapper`]($02c0a61f4d785504.md#sqlalchemy.orm.Mapper "sqlalchemy.orm.Mapper") which is the target of this event.
  12. - **class\_** – the mapped class.
  13. See also
  14. [`MapperEvents.before_configured()`](#sqlalchemy.orm.MapperEvents.before_configured "sqlalchemy.orm.MapperEvents.before_configured")
  15. [`MapperEvents.after_configured()`](#sqlalchemy.orm.MapperEvents.after_configured "sqlalchemy.orm.MapperEvents.after_configured")
  16. [`MapperEvents.before_mapper_configured()`](#sqlalchemy.orm.MapperEvents.before_mapper_configured "sqlalchemy.orm.MapperEvents.before_mapper_configured")

Instance Events

Instance events are focused on the construction of ORM mapped instances, including when they are instantiated as transient objects, when they are loaded from the database and become persistent objects, as well as when database refresh or expiration operations occur on the object.

Object NameDescription

InstanceEvents

Define events specific to object lifecycle.

class sqlalchemy.orm.``InstanceEvents

Define events specific to object lifecycle.

e.g.:

  1. from sqlalchemy import event
  2. def my_load_listener(target, context):
  3. print("on load!")
  4. event.listen(SomeClass, 'load', my_load_listener)

Available targets include:

  • mapped classes

  • unmapped superclasses of mapped or to-be-mapped classes (using the propagate=True flag)

  • Mapper objects

  • the Mapper class itself and the mapper() function indicate listening for all mappers.

Instance events are closely related to mapper events, but are more specific to the instance and its instrumentation, rather than its system of persistence.

When using InstanceEvents, several modifiers are available to the listen() function.

  • Parameters

    • propagate=False – When True, the event listener should be applied to all inheriting classes as well as the class which is the target of this listener.

    • raw=False – When True, the “target” argument passed to applicable event listener functions will be the instance’s InstanceState management object, rather than the mapped instance itself.

    • restore_load_context=False

      Applies to the InstanceEvents.load() and InstanceEvents.refresh() events. Restores the loader context of the object when the event hook is complete, so that ongoing eager load operations continue to target the object appropriately. A warning is emitted if the object is moved to a new loader context from within one of these events if this flag is not set.

      New in version 1.3.14.

Class signature

class sqlalchemy.orm.InstanceEvents (sqlalchemy.event.Events)

  • method sqlalchemy.orm.InstanceEvents.expire(target, attrs)

    Receive an object instance after its attributes or some subset have been expired.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeClass, 'expire')
  2. def receive_expire(target, attrs):
  3. "listen for the 'expire' event"
  4. # ... (event handling logic) ...
  5. ```
  6. ‘keys’ is a list of attribute names. If None, the entire state was expired.
  7. - Parameters
  8. - **target** – the mapped instance. If the event is configured with `raw=True`, this will instead be the [`InstanceState`]($346e0d9b88264a1f.md#sqlalchemy.orm.InstanceState "sqlalchemy.orm.InstanceState") state-management object associated with the instance.
  9. - **attrs** – sequence of attribute names which were expired, or None if all attributes were expired.
  • method sqlalchemy.orm.InstanceEvents.first_init(manager, cls)

    Called when the first instance of a particular mapping is called.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeClass, 'first_init')
  2. def receive_first_init(manager, cls):
  3. "listen for the 'first_init' event"
  4. # ... (event handling logic) ...
  5. ```
  6. This event is called when the `__init__` method of a class is called the first time for that particular class. The event invokes before `__init__` actually proceeds as well as before the [`InstanceEvents.init()`](#sqlalchemy.orm.InstanceEvents.init "sqlalchemy.orm.InstanceEvents.init") event is invoked.
  • method sqlalchemy.orm.InstanceEvents.init(target, args, kwargs)

    Receive an instance when its constructor is called.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeClass, 'init')
  2. def receive_init(target, args, kwargs):
  3. "listen for the 'init' event"
  4. # ... (event handling logic) ...
  5. ```
  6. This method is only called during a userland construction of an object, in conjunction with the object’s constructor, e.g. its `__init__` method. It is not called when an object is loaded from the database; see the [`InstanceEvents.load()`](#sqlalchemy.orm.InstanceEvents.load "sqlalchemy.orm.InstanceEvents.load") event in order to intercept a database load.
  7. The event is called before the actual `__init__` constructor of the object is called. The `kwargs` dictionary may be modified in-place in order to affect what is passed to `__init__`.
  8. - Parameters
  9. - **target** – the mapped instance. If the event is configured with `raw=True`, this will instead be the [`InstanceState`]($346e0d9b88264a1f.md#sqlalchemy.orm.InstanceState "sqlalchemy.orm.InstanceState") state-management object associated with the instance.
  10. - **args** – positional arguments passed to the `__init__` method. This is passed as a tuple and is currently immutable.
  11. - **kwargs** – keyword arguments passed to the `__init__` method. This structure *can* be altered in place.
  12. See also
  13. [`InstanceEvents.init_failure()`](#sqlalchemy.orm.InstanceEvents.init_failure "sqlalchemy.orm.InstanceEvents.init_failure")
  14. [`InstanceEvents.load()`](#sqlalchemy.orm.InstanceEvents.load "sqlalchemy.orm.InstanceEvents.load")
  • method sqlalchemy.orm.InstanceEvents.init_failure(target, args, kwargs)

    Receive an instance when its constructor has been called, and raised an exception.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeClass, 'init_failure')
  2. def receive_init_failure(target, args, kwargs):
  3. "listen for the 'init_failure' event"
  4. # ... (event handling logic) ...
  5. ```
  6. This method is only called during a userland construction of an object, in conjunction with the object’s constructor, e.g. its `__init__` method. It is not called when an object is loaded from the database.
  7. The event is invoked after an exception raised by the `__init__` method is caught. After the event is invoked, the original exception is re-raised outwards, so that the construction of the object still raises an exception. The actual exception and stack trace raised should be present in `sys.exc_info()`.
  8. - Parameters
  9. - **target** – the mapped instance. If the event is configured with `raw=True`, this will instead be the [`InstanceState`]($346e0d9b88264a1f.md#sqlalchemy.orm.InstanceState "sqlalchemy.orm.InstanceState") state-management object associated with the instance.
  10. - **args** – positional arguments that were passed to the `__init__` method.
  11. - **kwargs** – keyword arguments that were passed to the `__init__` method.
  12. See also
  13. [`InstanceEvents.init()`](#sqlalchemy.orm.InstanceEvents.init "sqlalchemy.orm.InstanceEvents.init")
  14. [`InstanceEvents.load()`](#sqlalchemy.orm.InstanceEvents.load "sqlalchemy.orm.InstanceEvents.load")
  • method sqlalchemy.orm.InstanceEvents.load(target, context)

    Receive an object instance after it has been created via __new__, and after initial attribute population has occurred.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeClass, 'load')
  2. def receive_load(target, context):
  3. "listen for the 'load' event"
  4. # ... (event handling logic) ...
  5. ```
  6. This typically occurs when the instance is created based on incoming result rows, and is only called once for that instance’s lifetime.
  7. Warning
  8. During a result-row load, this event is invoked when the first row received for this instance is processed. When using eager loading with collection-oriented attributes, the additional rows that are to be loaded / processed in order to load subsequent collection items have not occurred yet. This has the effect both that collections will not be fully loaded, as well as that if an operation occurs within this event handler that emits another database load operation for the object, the “loading context” for the object can change and interfere with the existing eager loaders still in progress.
  9. Examples of what can cause the “loading context” to change within the event handler include, but are not necessarily limited to:
  10. - accessing deferred attributes that weren’t part of the row, will trigger an “undefer” operation and refresh the object
  11. - accessing attributes on a joined-inheritance subclass that weren’t part of the row, will trigger a refresh operation.
  12. As of SQLAlchemy 1.3.14, a warning is emitted when this occurs. The [`InstanceEvents.restore_load_context`](#sqlalchemy.orm.InstanceEvents.params.restore_load_context "sqlalchemy.orm.InstanceEvents") option may be used on the event to prevent this warning; this will ensure that the existing loading context is maintained for the object after the event is called:
  13. ```
  14. @event.listens_for(
  15. SomeClass, "load", restore_load_context=True)
  16. def on_load(instance, context):
  17. instance.some_unloaded_attribute
  18. ```
  19. Changed in version 1.3.14: Added [`InstanceEvents.restore_load_context`](#sqlalchemy.orm.InstanceEvents.params.restore_load_context "sqlalchemy.orm.InstanceEvents") and [`SessionEvents.restore_load_context`](#sqlalchemy.orm.SessionEvents.params.restore_load_context "sqlalchemy.orm.SessionEvents") flags which apply to “on load” events, which will ensure that the loading context for an object is restored when the event hook is complete; a warning is emitted if the load context of the object changes without this flag being set.
  20. The [`InstanceEvents.load()`](#sqlalchemy.orm.InstanceEvents.load "sqlalchemy.orm.InstanceEvents.load") event is also available in a class-method decorator format called [`reconstructor()`]($948f146f80c064ce.md#sqlalchemy.orm.reconstructor "sqlalchemy.orm.reconstructor").
  21. - Parameters
  22. - **target** – the mapped instance. If the event is configured with `raw=True`, this will instead be the [`InstanceState`]($346e0d9b88264a1f.md#sqlalchemy.orm.InstanceState "sqlalchemy.orm.InstanceState") state-management object associated with the instance.
  23. - **context** – the [`QueryContext`]($346e0d9b88264a1f.md#sqlalchemy.orm.QueryContext "sqlalchemy.orm.QueryContext") corresponding to the current [`Query`]($3cf240505c8b4e45.md#sqlalchemy.orm.Query "sqlalchemy.orm.Query") in progress. This argument may be `None` if the load does not correspond to a [`Query`]($3cf240505c8b4e45.md#sqlalchemy.orm.Query "sqlalchemy.orm.Query"), such as during [`Session.merge()`]($2d92bd546622cf54.md#sqlalchemy.orm.Session.merge "sqlalchemy.orm.Session.merge").
  24. See also
  25. [`InstanceEvents.init()`](#sqlalchemy.orm.InstanceEvents.init "sqlalchemy.orm.InstanceEvents.init")
  26. [`InstanceEvents.refresh()`](#sqlalchemy.orm.InstanceEvents.refresh "sqlalchemy.orm.InstanceEvents.refresh")
  27. [`SessionEvents.loaded_as_persistent()`](#sqlalchemy.orm.SessionEvents.loaded_as_persistent "sqlalchemy.orm.SessionEvents.loaded_as_persistent")
  28. [Constructors and Object Initialization]($948f146f80c064ce.md#mapping-constructors)
  • method sqlalchemy.orm.InstanceEvents.pickle(target, state_dict)

    Receive an object instance when its associated state is being pickled.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeClass, 'pickle')
  2. def receive_pickle(target, state_dict):
  3. "listen for the 'pickle' event"
  4. # ... (event handling logic) ...
  5. ```
  6. - Parameters
  7. - **target** – the mapped instance. If the event is configured with `raw=True`, this will instead be the [`InstanceState`]($346e0d9b88264a1f.md#sqlalchemy.orm.InstanceState "sqlalchemy.orm.InstanceState") state-management object associated with the instance.
  8. - **state\_dict** – the dictionary returned by `__getstate__`, containing the state to be pickled.
  • method sqlalchemy.orm.InstanceEvents.refresh(target, context, attrs)

    Receive an object instance after one or more attributes have been refreshed from a query.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeClass, 'refresh')
  2. def receive_refresh(target, context, attrs):
  3. "listen for the 'refresh' event"
  4. # ... (event handling logic) ...
  5. ```
  6. Contrast this to the [`InstanceEvents.load()`](#sqlalchemy.orm.InstanceEvents.load "sqlalchemy.orm.InstanceEvents.load") method, which is invoked when the object is first loaded from a query.
  7. Note
  8. This event is invoked within the loader process before eager loaders may have been completed, and the object’s state may not be complete. Additionally, invoking row-level refresh operations on the object will place the object into a new loader context, interfering with the existing load context. See the note on [`InstanceEvents.load()`](#sqlalchemy.orm.InstanceEvents.load "sqlalchemy.orm.InstanceEvents.load") for background on making use of the [`InstanceEvents.restore_load_context`](#sqlalchemy.orm.InstanceEvents.params.restore_load_context "sqlalchemy.orm.InstanceEvents") parameter, in order to resolve this scenario.
  9. - Parameters
  10. - **target** – the mapped instance. If the event is configured with `raw=True`, this will instead be the [`InstanceState`]($346e0d9b88264a1f.md#sqlalchemy.orm.InstanceState "sqlalchemy.orm.InstanceState") state-management object associated with the instance.
  11. - **context** – the [`QueryContext`]($346e0d9b88264a1f.md#sqlalchemy.orm.QueryContext "sqlalchemy.orm.QueryContext") corresponding to the current [`Query`]($3cf240505c8b4e45.md#sqlalchemy.orm.Query "sqlalchemy.orm.Query") in progress.
  12. - **attrs** – sequence of attribute names which were populated, or None if all column-mapped, non-deferred attributes were populated.
  13. See also
  14. [`InstanceEvents.load()`](#sqlalchemy.orm.InstanceEvents.load "sqlalchemy.orm.InstanceEvents.load")
  • method sqlalchemy.orm.InstanceEvents.refresh_flush(target, flush_context, attrs)

    Receive an object instance after one or more attributes that contain a column-level default or onupdate handler have been refreshed during persistence of the object’s state.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeClass, 'refresh_flush')
  2. def receive_refresh_flush(target, flush_context, attrs):
  3. "listen for the 'refresh_flush' event"
  4. # ... (event handling logic) ...
  5. ```
  6. This event is the same as [`InstanceEvents.refresh()`](#sqlalchemy.orm.InstanceEvents.refresh "sqlalchemy.orm.InstanceEvents.refresh") except it is invoked within the unit of work flush process, and includes only non-primary-key columns that have column level default or onupdate handlers, including Python callables as well as server side defaults and triggers which may be fetched via the RETURNING clause.
  7. Note
  8. While the [`InstanceEvents.refresh_flush()`](#sqlalchemy.orm.InstanceEvents.refresh_flush "sqlalchemy.orm.InstanceEvents.refresh_flush") event is triggered for an object that was INSERTed as well as for an object that was UPDATEd, the event is geared primarily towards the UPDATE process; it is mostly an internal artifact that INSERT actions can also trigger this event, and note that **primary key columns for an INSERTed row are explicitly omitted** from this event. In order to intercept the newly INSERTed state of an object, the [`SessionEvents.pending_to_persistent()`](#sqlalchemy.orm.SessionEvents.pending_to_persistent "sqlalchemy.orm.SessionEvents.pending_to_persistent") and [`MapperEvents.after_insert()`](#sqlalchemy.orm.MapperEvents.after_insert "sqlalchemy.orm.MapperEvents.after_insert") are better choices.
  9. New in version 1.0.5.
  10. - Parameters
  11. - **target** – the mapped instance. If the event is configured with `raw=True`, this will instead be the [`InstanceState`]($346e0d9b88264a1f.md#sqlalchemy.orm.InstanceState "sqlalchemy.orm.InstanceState") state-management object associated with the instance.
  12. - **flush\_context** – Internal [`UOWTransaction`]($346e0d9b88264a1f.md#sqlalchemy.orm.UOWTransaction "sqlalchemy.orm.UOWTransaction") object which handles the details of the flush.
  13. - **attrs** – sequence of attribute names which were populated.
  14. See also
  15. [Fetching Server-Generated Defaults]($40343ee29299c061.md#orm-server-defaults)
  16. [Column INSERT/UPDATE Defaults]($42c00eeb4c391fb1.md)
  • method sqlalchemy.orm.InstanceEvents.unpickle(target, state_dict)

    Receive an object instance after its associated state has been unpickled.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeClass, 'unpickle')
  2. def receive_unpickle(target, state_dict):
  3. "listen for the 'unpickle' event"
  4. # ... (event handling logic) ...
  5. ```
  6. - Parameters
  7. - **target** – the mapped instance. If the event is configured with `raw=True`, this will instead be the [`InstanceState`]($346e0d9b88264a1f.md#sqlalchemy.orm.InstanceState "sqlalchemy.orm.InstanceState") state-management object associated with the instance.
  8. - **state\_dict** – the dictionary sent to `__setstate__`, containing the state dictionary which was pickled.

Attribute Events

Attribute events are triggered as things occur on individual attributes of ORM mapped objects. These events form the basis for things like custom validation functions as well as backref handlers.

See also

Changing Attribute Behavior

Object NameDescription

AttributeEvents

Define events for object attributes.

class sqlalchemy.orm.``AttributeEvents

Define events for object attributes.

These are typically defined on the class-bound descriptor for the target class.

e.g.:

  1. from sqlalchemy import event
  2. @event.listens_for(MyClass.collection, 'append', propagate=True)
  3. def my_append_listener(target, value, initiator):
  4. print("received append event for target: %s" % target)

Listeners have the option to return a possibly modified version of the value, when the AttributeEvents.retval flag is passed to listen() or listens_for():

  1. def validate_phone(target, value, oldvalue, initiator):
  2. "Strip non-numeric characters from a phone number"
  3. return re.sub(r'\D', '', value)
  4. # setup listener on UserContact.phone attribute, instructing
  5. # it to use the return value
  6. listen(UserContact.phone, 'set', validate_phone, retval=True)

A validation function like the above can also raise an exception such as ValueError to halt the operation.

The AttributeEvents.propagate flag is also important when applying listeners to mapped classes that also have mapped subclasses, as when using mapper inheritance patterns:

  1. @event.listens_for(MySuperClass.attr, 'set', propagate=True)
  2. def receive_set(target, value, initiator):
  3. print("value set: %s" % target)

The full list of modifiers available to the listen() and listens_for() functions are below.

  • Parameters

    • active_history=False – When True, indicates that the “set” event would like to receive the “old” value being replaced unconditionally, even if this requires firing off database loads. Note that active_history can also be set directly via column_property() and relationship().

    • propagate=False – When True, the listener function will be established not just for the class attribute given, but for attributes of the same name on all current subclasses of that class, as well as all future subclasses of that class, using an additional listener that listens for instrumentation events.

    • raw=False – When True, the “target” argument to the event will be the InstanceState management object, rather than the mapped instance itself.

    • retval=False – when True, the user-defined event listening must return the “value” argument from the function. This gives the listening function the opportunity to change the value that is ultimately used for a “set” or “append” event.

Class signature

class sqlalchemy.orm.AttributeEvents (sqlalchemy.event.Events)

  • method sqlalchemy.orm.AttributeEvents.append(target, value, initiator)

    Receive a collection append event.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeClass.some_attribute, 'append')
  2. def receive_append(target, value, initiator):
  3. "listen for the 'append' event"
  4. # ... (event handling logic) ...
  5. ```
  6. The append event is invoked for each element as it is appended to the collection. This occurs for single-item appends as well as for a “bulk replace” operation.
  7. - Parameters
  8. - **target** – the object instance receiving the event. If the listener is registered with `raw=True`, this will be the [`InstanceState`]($346e0d9b88264a1f.md#sqlalchemy.orm.InstanceState "sqlalchemy.orm.InstanceState") object.
  9. - **value** – the value being appended. If this listener is registered with `retval=True`, the listener function must return this value, or a new value which replaces it.
  10. - **initiator** – An instance of `Event` representing the initiation of the event. May be modified from its original value by backref handlers in order to control chained event propagation, as well as be inspected for information about the source of the event.
  11. Returns
  12. if the event was registered with `retval=True`, the given value, or a new effective value, should be returned.
  13. See also
  14. [`AttributeEvents`](#sqlalchemy.orm.AttributeEvents "sqlalchemy.orm.AttributeEvents") - background on listener options such as propagation to subclasses.
  15. [`AttributeEvents.bulk_replace()`](#sqlalchemy.orm.AttributeEvents.bulk_replace "sqlalchemy.orm.AttributeEvents.bulk_replace")
  • method sqlalchemy.orm.AttributeEvents.bulk_replace(target, values, initiator)

    Receive a collection ‘bulk replace’ event.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeClass.some_attribute, 'bulk_replace')
  2. def receive_bulk_replace(target, values, initiator):
  3. "listen for the 'bulk_replace' event"
  4. # ... (event handling logic) ...
  5. ```
  6. This event is invoked for a sequence of values as they are incoming to a bulk collection set operation, which can be modified in place before the values are treated as ORM objects. This is an “early hook” that runs before the bulk replace routine attempts to reconcile which objects are already present in the collection and which are being removed by the net replace operation.
  7. It is typical that this method be combined with use of the [`AttributeEvents.append()`](#sqlalchemy.orm.AttributeEvents.append "sqlalchemy.orm.AttributeEvents.append") event. When using both of these events, note that a bulk replace operation will invoke the [`AttributeEvents.append()`](#sqlalchemy.orm.AttributeEvents.append "sqlalchemy.orm.AttributeEvents.append") event for all new items, even after [`AttributeEvents.bulk_replace()`](#sqlalchemy.orm.AttributeEvents.bulk_replace "sqlalchemy.orm.AttributeEvents.bulk_replace") has been invoked for the collection as a whole. In order to determine if an [`AttributeEvents.append()`](#sqlalchemy.orm.AttributeEvents.append "sqlalchemy.orm.AttributeEvents.append") event is part of a bulk replace, use the symbol `attributes.OP_BULK_REPLACE` to test the incoming initiator:
  8. ```
  9. from sqlalchemy.orm.attributes import OP_BULK_REPLACE
  10. @event.listens_for(SomeObject.collection, "bulk_replace")
  11. def process_collection(target, values, initiator):
  12. values[:] = [_make_value(value) for value in values]
  13. @event.listens_for(SomeObject.collection, "append", retval=True)
  14. def process_collection(target, value, initiator):
  15. # make sure bulk_replace didn't already do it
  16. if initiator is None or initiator.op is not OP_BULK_REPLACE:
  17. return _make_value(value)
  18. else:
  19. return value
  20. ```
  21. New in version 1.2.
  22. - Parameters
  23. - **target** – the object instance receiving the event. If the listener is registered with `raw=True`, this will be the [`InstanceState`]($346e0d9b88264a1f.md#sqlalchemy.orm.InstanceState "sqlalchemy.orm.InstanceState") object.
  24. - **value** – a sequence (e.g. a list) of the values being set. The handler can modify this list in place.
  25. - **initiator** – An instance of `Event` representing the initiation of the event.
  26. See also
  27. [`AttributeEvents`](#sqlalchemy.orm.AttributeEvents "sqlalchemy.orm.AttributeEvents") - background on listener options such as propagation to subclasses.
  • method sqlalchemy.orm.AttributeEvents.dispose_collection(target, collection, collection_adapter)

    Receive a ‘collection dispose’ event.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeClass.some_attribute, 'dispose_collection')
  2. def receive_dispose_collection(target, collection, collection_adapter):
  3. "listen for the 'dispose_collection' event"
  4. # ... (event handling logic) ...
  5. ```
  6. This event is triggered for a collection-based attribute when a collection is replaced, that is:
  7. ```
  8. u1.addresses.append(a1)
  9. u1.addresses = [a2, a3] # <- old collection is disposed
  10. ```
  11. The old collection received will contain its previous contents.
  12. Changed in version 1.2: The collection passed to [`AttributeEvents.dispose_collection()`](#sqlalchemy.orm.AttributeEvents.dispose_collection "sqlalchemy.orm.AttributeEvents.dispose_collection") will now have its contents before the dispose intact; previously, the collection would be empty.
  13. New in version 1.0.0: the [`AttributeEvents.init_collection()`](#sqlalchemy.orm.AttributeEvents.init_collection "sqlalchemy.orm.AttributeEvents.init_collection") and [`AttributeEvents.dispose_collection()`](#sqlalchemy.orm.AttributeEvents.dispose_collection "sqlalchemy.orm.AttributeEvents.dispose_collection") events.
  14. See also
  15. [`AttributeEvents`](#sqlalchemy.orm.AttributeEvents "sqlalchemy.orm.AttributeEvents") - background on listener options such as propagation to subclasses.
  • method sqlalchemy.orm.AttributeEvents.init_collection(target, collection, collection_adapter)

    Receive a ‘collection init’ event.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeClass.some_attribute, 'init_collection')
  2. def receive_init_collection(target, collection, collection_adapter):
  3. "listen for the 'init_collection' event"
  4. # ... (event handling logic) ...
  5. ```
  6. This event is triggered for a collection-based attribute, when the initial “empty collection” is first generated for a blank attribute, as well as for when the collection is replaced with a new one, such as via a set event.
  7. E.g., given that `User.addresses` is a relationship-based collection, the event is triggered here:
  8. ```
  9. u1 = User()
  10. u1.addresses.append(a1) # <- new collection
  11. ```
  12. and also during replace operations:
  13. ```
  14. u1.addresses = [a2, a3] # <- new collection
  15. ```
  16. - Parameters
  17. - **target** – the object instance receiving the event. If the listener is registered with `raw=True`, this will be the [`InstanceState`]($346e0d9b88264a1f.md#sqlalchemy.orm.InstanceState "sqlalchemy.orm.InstanceState") object.
  18. - **collection** – the new collection. This will always be generated from what was specified as [`relationship.collection_class`]($7c85a873b6a4b509.md#sqlalchemy.orm.relationship.params.collection_class "sqlalchemy.orm.relationship"), and will always be empty.
  19. - **collection\_adapter** – the [`CollectionAdapter`]($584f99c49dcec30d.md#sqlalchemy.orm.collections.CollectionAdapter "sqlalchemy.orm.collections.CollectionAdapter") that will mediate internal access to the collection.
  20. New in version 1.0.0: [`AttributeEvents.init_collection()`](#sqlalchemy.orm.AttributeEvents.init_collection "sqlalchemy.orm.AttributeEvents.init_collection") and [`AttributeEvents.dispose_collection()`](#sqlalchemy.orm.AttributeEvents.dispose_collection "sqlalchemy.orm.AttributeEvents.dispose_collection") events.
  21. See also
  22. [`AttributeEvents`](#sqlalchemy.orm.AttributeEvents "sqlalchemy.orm.AttributeEvents") - background on listener options such as propagation to subclasses.
  23. [`AttributeEvents.init_scalar()`](#sqlalchemy.orm.AttributeEvents.init_scalar "sqlalchemy.orm.AttributeEvents.init_scalar") - “scalar” version of this event.
  • method sqlalchemy.orm.AttributeEvents.init_scalar(target, value, dict_)

    Receive a scalar “init” event.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeClass.some_attribute, 'init_scalar')
  2. def receive_init_scalar(target, value, dict_):
  3. "listen for the 'init_scalar' event"
  4. # ... (event handling logic) ...
  5. ```
  6. This event is invoked when an uninitialized, unpersisted scalar attribute is accessed, e.g. read:
  7. ```
  8. x = my_object.some_attribute
  9. ```
  10. The ORM’s default behavior when this occurs for an un-initialized attribute is to return the value `None`; note this differs from Python’s usual behavior of raising `AttributeError`. The event here can be used to customize what value is actually returned, with the assumption that the event listener would be mirroring a default generator that is configured on the Core [`Column`]($b6b7014c5dbcfa2c.md#sqlalchemy.schema.Column "sqlalchemy.schema.Column") object as well.
  11. Since a default generator on a [`Column`]($b6b7014c5dbcfa2c.md#sqlalchemy.schema.Column "sqlalchemy.schema.Column") might also produce a changing value such as a timestamp, the [`AttributeEvents.init_scalar()`](#sqlalchemy.orm.AttributeEvents.init_scalar "sqlalchemy.orm.AttributeEvents.init_scalar") event handler can also be used to **set** the newly returned value, so that a Core-level default generation function effectively fires off only once, but at the moment the attribute is accessed on the non-persisted object. Normally, no change to the object’s state is made when an uninitialized attribute is accessed (much older SQLAlchemy versions did in fact change the object’s state).
  12. If a default generator on a column returned a particular constant, a handler might be used as follows:
  13. ```
  14. SOME_CONSTANT = 3.1415926
  15. class MyClass(Base):
  16. # ...
  17. some_attribute = Column(Numeric, default=SOME_CONSTANT)
  18. @event.listens_for(
  19. MyClass.some_attribute, "init_scalar",
  20. retval=True, propagate=True)
  21. def _init_some_attribute(target, dict_, value):
  22. dict_['some_attribute'] = SOME_CONSTANT
  23. return SOME_CONSTANT
  24. ```
  25. Above, we initialize the attribute `MyClass.some_attribute` to the value of `SOME_CONSTANT`. The above code includes the following features:
  26. - By setting the value `SOME_CONSTANT` in the given `dict_`, we indicate that this value is to be persisted to the database. This supersedes the use of `SOME_CONSTANT` in the default generator for the [`Column`]($b6b7014c5dbcfa2c.md#sqlalchemy.schema.Column "sqlalchemy.schema.Column"). The `active_column_defaults.py` example given at [Attribute Instrumentation]($2c0b4d5f30e4919a.md#examples-instrumentation) illustrates using the same approach for a changing default, e.g. a timestamp generator. In this particular example, it is not strictly necessary to do this since `SOME_CONSTANT` would be part of the INSERT statement in either case.
  27. - By establishing the `retval=True` flag, the value we return from the function will be returned by the attribute getter. Without this flag, the event is assumed to be a passive observer and the return value of our function is ignored.
  28. - The `propagate=True` flag is significant if the mapped class includes inheriting subclasses, which would also make use of this event listener. Without this flag, an inheriting subclass will not use our event handler.
  29. In the above example, the attribute set event [`AttributeEvents.set()`](#sqlalchemy.orm.AttributeEvents.set "sqlalchemy.orm.AttributeEvents.set") as well as the related validation feature provided by [`validates`]($b423b32ef48b9a7a.md#sqlalchemy.orm.validates "sqlalchemy.orm.validates") is **not** invoked when we apply our value to the given `dict_`. To have these events to invoke in response to our newly generated value, apply the value to the given object as a normal attribute set operation:
  30. ```
  31. SOME_CONSTANT = 3.1415926
  32. @event.listens_for(
  33. MyClass.some_attribute, "init_scalar",
  34. retval=True, propagate=True)
  35. def _init_some_attribute(target, dict_, value):
  36. # will also fire off attribute set events
  37. target.some_attribute = SOME_CONSTANT
  38. return SOME_CONSTANT
  39. ```
  40. When multiple listeners are set up, the generation of the value is “chained” from one listener to the next by passing the value returned by the previous listener that specifies `retval=True` as the `value` argument of the next listener.
  41. New in version 1.1.
  42. - Parameters
  43. - **target** – the object instance receiving the event. If the listener is registered with `raw=True`, this will be the [`InstanceState`]($346e0d9b88264a1f.md#sqlalchemy.orm.InstanceState "sqlalchemy.orm.InstanceState") object.
  44. - **value** – the value that is to be returned before this event listener were invoked. This value begins as the value `None`, however will be the return value of the previous event handler function if multiple listeners are present.
  45. - **dict\_** – the attribute dictionary of this mapped object. This is normally the `__dict__` of the object, but in all cases represents the destination that the attribute system uses to get at the actual value of this attribute. Placing the value in this dictionary has the effect that the value will be used in the INSERT statement generated by the unit of work.
  46. See also
  47. [`AttributeEvents.init_collection()`](#sqlalchemy.orm.AttributeEvents.init_collection "sqlalchemy.orm.AttributeEvents.init_collection") - collection version of this event
  48. [`AttributeEvents`](#sqlalchemy.orm.AttributeEvents "sqlalchemy.orm.AttributeEvents") - background on listener options such as propagation to subclasses.
  49. [Attribute Instrumentation]($2c0b4d5f30e4919a.md#examples-instrumentation) - see the `active_column_defaults.py` example.
  • method sqlalchemy.orm.AttributeEvents.modified(target, initiator)

    Receive a ‘modified’ event.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeClass.some_attribute, 'modified')
  2. def receive_modified(target, initiator):
  3. "listen for the 'modified' event"
  4. # ... (event handling logic) ...
  5. ```
  6. This event is triggered when the [`flag_modified()`]($2d92bd546622cf54.md#sqlalchemy.orm.attributes.flag_modified "sqlalchemy.orm.attributes.flag_modified") function is used to trigger a modify event on an attribute without any specific value being set.
  7. New in version 1.2.
  8. - Parameters
  9. - **target** – the object instance receiving the event. If the listener is registered with `raw=True`, this will be the [`InstanceState`]($346e0d9b88264a1f.md#sqlalchemy.orm.InstanceState "sqlalchemy.orm.InstanceState") object.
  10. - **initiator** – An instance of `Event` representing the initiation of the event.
  11. See also
  12. [`AttributeEvents`](#sqlalchemy.orm.AttributeEvents "sqlalchemy.orm.AttributeEvents") - background on listener options such as propagation to subclasses.
  • method sqlalchemy.orm.AttributeEvents.remove(target, value, initiator)

    Receive a collection remove event.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeClass.some_attribute, 'remove')
  2. def receive_remove(target, value, initiator):
  3. "listen for the 'remove' event"
  4. # ... (event handling logic) ...
  5. ```
  6. - Parameters
  7. - **target** – the object instance receiving the event. If the listener is registered with `raw=True`, this will be the [`InstanceState`]($346e0d9b88264a1f.md#sqlalchemy.orm.InstanceState "sqlalchemy.orm.InstanceState") object.
  8. - **value** – the value being removed.
  9. - **initiator** –
  10. An instance of `Event` representing the initiation of the event. May be modified from its original value by backref handlers in order to control chained event propagation.
  11. Changed in version 0.9.0: the `initiator` argument is now passed as a `Event` object, and may be modified by backref handlers within a chain of backref-linked events.
  12. Returns
  13. No return value is defined for this event.
  14. See also
  15. [`AttributeEvents`](#sqlalchemy.orm.AttributeEvents "sqlalchemy.orm.AttributeEvents") - background on listener options such as propagation to subclasses.
  • method sqlalchemy.orm.AttributeEvents.set(target, value, oldvalue, initiator)

    Receive a scalar set event.

    Example argument forms:

    ``` from sqlalchemy import event

  1. @event.listens_for(SomeClass.some_attribute, 'set')
  2. def receive_set(target, value, oldvalue, initiator):
  3. "listen for the 'set' event"
  4. # ... (event handling logic) ...
  5. ```
  6. - Parameters
  7. - **target** – the object instance receiving the event. If the listener is registered with `raw=True`, this will be the [`InstanceState`]($346e0d9b88264a1f.md#sqlalchemy.orm.InstanceState "sqlalchemy.orm.InstanceState") object.
  8. - **value** – the value being set. If this listener is registered with `retval=True`, the listener function must return this value, or a new value which replaces it.
  9. - **oldvalue** – the previous value being replaced. This may also be the symbol `NEVER_SET` or `NO_VALUE`. If the listener is registered with `active_history=True`, the previous value of the attribute will be loaded from the database if the existing value is currently unloaded or expired.
  10. - **initiator** –
  11. An instance of `Event` representing the initiation of the event. May be modified from its original value by backref handlers in order to control chained event propagation.
  12. Changed in version 0.9.0: the `initiator` argument is now passed as a `Event` object, and may be modified by backref handlers within a chain of backref-linked events.
  13. Returns
  14. if the event was registered with `retval=True`, the given value, or a new effective value, should be returned.
  15. See also
  16. [`AttributeEvents`](#sqlalchemy.orm.AttributeEvents "sqlalchemy.orm.AttributeEvents") - background on listener options such as propagation to subclasses.

Query Events

Object NameDescription

QueryEvents

Represent events within the construction of a Query object.

class sqlalchemy.orm.``QueryEvents

Represent events within the construction of a Query object.

The QueryEvents hooks are now superseded by the SessionEvents.do_orm_execute() event hook.

Class signature

class sqlalchemy.orm.QueryEvents (sqlalchemy.event.Events)

  1. @event.listens_for(SomeQuery, 'before_compile')
  2. def receive_before_compile(query):
  3. "listen for the 'before_compile' event"
  4. # ... (event handling logic) ...
  5. ```
  6. Deprecated since version 1.4: The [`QueryEvents.before_compile()`](#sqlalchemy.orm.QueryEvents.before_compile "sqlalchemy.orm.QueryEvents.before_compile") event is superseded by the much more capable [`SessionEvents.do_orm_execute()`](#sqlalchemy.orm.SessionEvents.do_orm_execute "sqlalchemy.orm.SessionEvents.do_orm_execute") hook. In version 1.4, the [`QueryEvents.before_compile()`](#sqlalchemy.orm.QueryEvents.before_compile "sqlalchemy.orm.QueryEvents.before_compile") event is **no longer used** for ORM-level attribute loads, such as loads of deferred or expired attributes as well as relationship loaders. See the new examples in [ORM Query Events]($2c0b4d5f30e4919a.md#examples-session-orm-events) which illustrate new ways of intercepting and modifying ORM queries for the most common purpose of adding arbitrary filter criteria.
  7. This event is intended to allow changes to the query given:
  8. ```
  9. @event.listens_for(Query, "before_compile", retval=True)
  10. def no_deleted(query):
  11. for desc in query.column_descriptions:
  12. if desc['type'] is User:
  13. entity = desc['entity']
  14. query = query.filter(entity.deleted == False)
  15. return query
  16. ```
  17. The event should normally be listened with the `retval=True` parameter set, so that the modified query may be returned.
  18. The [`QueryEvents.before_compile()`](#sqlalchemy.orm.QueryEvents.before_compile "sqlalchemy.orm.QueryEvents.before_compile") event by default will disallow “baked” queries from caching a query, if the event hook returns a new [`Query`]($3cf240505c8b4e45.md#sqlalchemy.orm.Query "sqlalchemy.orm.Query") object. This affects both direct use of the baked query extension as well as its operation within lazy loaders and eager loaders for relationships. In order to re-establish the query being cached, apply the event adding the `bake_ok` flag:
  19. ```
  20. @event.listens_for(
  21. Query, "before_compile", retval=True, bake_ok=True)
  22. def my_event(query):
  23. for desc in query.column_descriptions:
  24. if desc['type'] is User:
  25. entity = desc['entity']
  26. query = query.filter(entity.deleted == False)
  27. return query
  28. ```
  29. When `bake_ok` is set to True, the event hook will only be invoked once, and not called for subsequent invocations of a particular query that is being cached.
  30. New in version 1.3.11: - added the “bake\_ok” flag to the [`QueryEvents.before_compile()`](#sqlalchemy.orm.QueryEvents.before_compile "sqlalchemy.orm.QueryEvents.before_compile") event and disallowed caching via the “baked” extension from occurring for event handlers that return a new [`Query`]($3cf240505c8b4e45.md#sqlalchemy.orm.Query "sqlalchemy.orm.Query") object if this flag is not set.
  31. See also
  32. [`QueryEvents.before_compile_update()`](#sqlalchemy.orm.QueryEvents.before_compile_update "sqlalchemy.orm.QueryEvents.before_compile_update")
  33. [`QueryEvents.before_compile_delete()`](#sqlalchemy.orm.QueryEvents.before_compile_delete "sqlalchemy.orm.QueryEvents.before_compile_delete")
  34. [Using the before\_compile event]($1e294cfa5cf1dc2c.md#baked-with-before-compile)
  1. @event.listens_for(SomeQuery, 'before_compile_delete')
  2. def receive_before_compile_delete(query, delete_context):
  3. "listen for the 'before_compile_delete' event"
  4. # ... (event handling logic) ...
  5. ```
  6. Deprecated since version 1.4: The [`QueryEvents.before_compile_delete()`](#sqlalchemy.orm.QueryEvents.before_compile_delete "sqlalchemy.orm.QueryEvents.before_compile_delete") event is superseded by the much more capable [`SessionEvents.do_orm_execute()`](#sqlalchemy.orm.SessionEvents.do_orm_execute "sqlalchemy.orm.SessionEvents.do_orm_execute") hook.
  7. Like the [`QueryEvents.before_compile()`](#sqlalchemy.orm.QueryEvents.before_compile "sqlalchemy.orm.QueryEvents.before_compile") event, this event should be configured with `retval=True`, and the modified [`Query`]($3cf240505c8b4e45.md#sqlalchemy.orm.Query "sqlalchemy.orm.Query") object returned, as in
  8. ```
  9. @event.listens_for(Query, "before_compile_delete", retval=True)
  10. def no_deleted(query, delete_context):
  11. for desc in query.column_descriptions:
  12. if desc['type'] is User:
  13. entity = desc['entity']
  14. query = query.filter(entity.deleted == False)
  15. return query
  16. ```
  17. - Parameters
  18. - **query** – a [`Query`]($3cf240505c8b4e45.md#sqlalchemy.orm.Query "sqlalchemy.orm.Query") instance; this is also the `.query` attribute of the given “delete context” object.
  19. - **delete\_context** – a “delete context” object which is the same kind of object as described in `QueryEvents.after_bulk_delete.delete_context`.
  20. New in version 1.2.17.
  21. See also
  22. [`QueryEvents.before_compile()`](#sqlalchemy.orm.QueryEvents.before_compile "sqlalchemy.orm.QueryEvents.before_compile")
  23. [`QueryEvents.before_compile_update()`](#sqlalchemy.orm.QueryEvents.before_compile_update "sqlalchemy.orm.QueryEvents.before_compile_update")
  1. @event.listens_for(SomeQuery, 'before_compile_update')
  2. def receive_before_compile_update(query, update_context):
  3. "listen for the 'before_compile_update' event"
  4. # ... (event handling logic) ...
  5. ```
  6. Deprecated since version 1.4: The [`QueryEvents.before_compile_update()`](#sqlalchemy.orm.QueryEvents.before_compile_update "sqlalchemy.orm.QueryEvents.before_compile_update") event is superseded by the much more capable [`SessionEvents.do_orm_execute()`](#sqlalchemy.orm.SessionEvents.do_orm_execute "sqlalchemy.orm.SessionEvents.do_orm_execute") hook.
  7. Like the [`QueryEvents.before_compile()`](#sqlalchemy.orm.QueryEvents.before_compile "sqlalchemy.orm.QueryEvents.before_compile") event, if the event is to be used to alter the [`Query`]($3cf240505c8b4e45.md#sqlalchemy.orm.Query "sqlalchemy.orm.Query") object, it should be configured with `retval=True`, and the modified [`Query`]($3cf240505c8b4e45.md#sqlalchemy.orm.Query "sqlalchemy.orm.Query") object returned, as in
  8. ```
  9. @event.listens_for(Query, "before_compile_update", retval=True)
  10. def no_deleted(query, update_context):
  11. for desc in query.column_descriptions:
  12. if desc['type'] is User:
  13. entity = desc['entity']
  14. query = query.filter(entity.deleted == False)
  15. update_context.values['timestamp'] = datetime.utcnow()
  16. return query
  17. ```
  18. The `.values` dictionary of the “update context” object can also be modified in place as illustrated above.
  19. - Parameters
  20. - **query** – a [`Query`]($3cf240505c8b4e45.md#sqlalchemy.orm.Query "sqlalchemy.orm.Query") instance; this is also the `.query` attribute of the given “update context” object.
  21. - **update\_context** – an “update context” object which is the same kind of object as described in `QueryEvents.after_bulk_update.update_context`. The object has a `.values` attribute in an UPDATE context which is the dictionary of parameters passed to [`Query.update()`]($3cf240505c8b4e45.md#sqlalchemy.orm.Query.update "sqlalchemy.orm.Query.update"). This dictionary can be modified to alter the VALUES clause of the resulting UPDATE statement.
  22. New in version 1.2.17.
  23. See also
  24. [`QueryEvents.before_compile()`](#sqlalchemy.orm.QueryEvents.before_compile "sqlalchemy.orm.QueryEvents.before_compile")
  25. [`QueryEvents.before_compile_delete()`](#sqlalchemy.orm.QueryEvents.before_compile_delete "sqlalchemy.orm.QueryEvents.before_compile_delete")

Instrumentation Events

Defines SQLAlchemy’s system of class instrumentation.

This module is usually not directly visible to user applications, but defines a large part of the ORM’s interactivity.

instrumentation.py deals with registration of end-user classes for state tracking. It interacts closely with state.py and attributes.py which establish per-instance and per-class-attribute instrumentation, respectively.

The class instrumentation system can be customized on a per-class or global basis using the sqlalchemy.ext.instrumentation module, which provides the means to build and specify alternate instrumentation forms.

Object NameDescription

InstrumentationEvents

Events related to class instrumentation events.

class sqlalchemy.orm.``InstrumentationEvents

Events related to class instrumentation events.

The listeners here support being established against any new style class, that is any object that is a subclass of ‘type’. Events will then be fired off for events against that class. If the “propagate=True” flag is passed to event.listen(), the event will fire off for subclasses of that class as well.

The Python type builtin is also accepted as a target, which when used has the effect of events being emitted for all classes.

Note the “propagate” flag here is defaulted to True, unlike the other class level events where it defaults to False. This means that new subclasses will also be the subject of these events, when a listener is established on a superclass.

Class signature

class sqlalchemy.orm.InstrumentationEvents (sqlalchemy.event.Events)

  1. @event.listens_for(SomeBaseClass, 'attribute_instrument')
  2. def receive_attribute_instrument(cls, key, inst):
  3. "listen for the 'attribute_instrument' event"
  4. # ... (event handling logic) ...
  5. ```
  1. @event.listens_for(SomeBaseClass, 'class_instrument')
  2. def receive_class_instrument(cls):
  3. "listen for the 'class_instrument' event"
  4. # ... (event handling logic) ...
  5. ```
  6. To get at the [`ClassManager`]($346e0d9b88264a1f.md#sqlalchemy.orm.ClassManager "sqlalchemy.orm.ClassManager"), use `manager_of_class()`.
  1. @event.listens_for(SomeBaseClass, 'class_uninstrument')
  2. def receive_class_uninstrument(cls):
  3. "listen for the 'class_uninstrument' event"
  4. # ... (event handling logic) ...
  5. ```
  6. To get at the [`ClassManager`]($346e0d9b88264a1f.md#sqlalchemy.orm.ClassManager "sqlalchemy.orm.ClassManager"), use `manager_of_class()`.