class documentation

class MapperEvents(event.Events):

Known subclasses: sqlalchemy.orm.events._MapperEventsHold.HoldMapperEvents

View In Hierarchy

Define events specific to mappings.

e.g.:

from sqlalchemy import event

def my_before_insert_listener(mapper, connection, target):
    # execute a stored procedure upon INSERT,
    # apply the value to the row to be inserted
    target.calculated_value = connection.execute(
        text("select my_special_function(%d)" % target.special_number)
    ).scalar()

# associate the listener function with SomeClass,
# to execute during the "before_insert" hook
event.listen(
    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)
  • _orm.Mapper objects
  • the _orm.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 .event.listen function.

Parameters
propagate=​FalseWhen 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=​FalseWhen 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 Method ​_accept​_with Undocumented
Class Method ​_clear Undocumented
Class Method ​_listen Undocumented
Class Method ​_new​_mapper​_instance Undocumented
Method after​_configured Called after a series of mappers have been configured.
Method after​_delete Receive an object instance after a DELETE statement has been emitted corresponding to that instance.
Method after​_insert Receive an object instance after an INSERT statement is emitted corresponding to that instance.
Method after​_update Receive an object instance after an UPDATE statement is emitted corresponding to that instance.
Method before​_configured Called before a series of mappers have been configured.
Method before​_delete Receive an object instance before a DELETE statement is emitted corresponding to that instance.
Method before​_insert Receive an object instance before an INSERT statement is emitted corresponding to that instance.
Method before​_mapper​_configured Called right before a specific mapper is to be configured.
Method before​_update Receive an object instance before an UPDATE statement is emitted corresponding to that instance.
Method instrument​_class Receive a class when the mapper is first constructed, before instrumentation is applied to the mapped class.
Method mapper​_configured Called when a specific mapper has completed its own configuration within the scope of the .configure_mappers call.
Class Variable ​_target​_class​_doc Undocumented

Inherited from Events:

Class Method ​_remove Undocumented
Static Method ​_set​_dispatch Undocumented
@classmethod
@util.preload_module('sqlalchemy.orm')
def _accept_with(cls, target):
@classmethod
def _clear(cls):

Undocumented

@classmethod
def _listen(cls, event_key, raw=False, retval=False, propagate=False, **kw):

Undocumented

@classmethod
def _new_mapper_instance(cls, class_, mapper):

Undocumented

def after_configured(self):

Called after a series of mappers have been configured.

The .MapperEvents.after_configured event is invoked each time the _orm.configure_mappers function is invoked, after the function has completed its work. _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.

Contrast this event to the .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, which is invoked before the series of mappers has been configured.

This event can only be applied to the _orm.Mapper class or .mapper function, and not to individual mappings or mapped classes. It is only invoked for all mappings as a whole:

from sqlalchemy.orm import mapper

@event.listens_for(mapper, "after_configured")
def go():
    # ...

Theoretically this event is called once per application, but is actually called any time new mappers have been affected by a _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:

from sqlalchemy.orm import mapper

@event.listens_for(mapper, "after_configured", once=True)
def go():
    # ...

See Also

.MapperEvents.before_mapper_configured

.MapperEvents.mapper_configured

.MapperEvents.before_configured

def after_delete(self, mapper, connection, target):

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

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.

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.

Warning

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 _engine.Connection. Please read fully the notes at :ref:`session_persistence_mapper` for guidelines on using these methods; generally, the .SessionEvents.before_flush method should be preferred for general on-flush changes.

Parameters
mapperthe _orm.Mapper which is the target of this event.
connectionthe _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.
targetthe mapped instance being deleted. If the event is configured with raw=True, this will instead be the .InstanceState state-management object associated with the instance.
Returns
No return value is supported by this event.
def after_insert(self, mapper, connection, target):

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

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.

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 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.

Warning

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 _engine.Connection. Please read fully the notes at :ref:`session_persistence_mapper` for guidelines on using these methods; generally, the .SessionEvents.before_flush method should be preferred for general on-flush changes.

Parameters
mapperthe _orm.Mapper which is the target of this event.
connectionthe _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.
targetthe mapped instance being persisted. If the event is configured with raw=True, this will instead be the .InstanceState state-management object associated with the instance.
Returns
No return value is supported by this event.
def after_update(self, mapper, connection, target):

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

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.

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 is not a guarantee that an UPDATE statement has been issued.

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).

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 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.

Warning

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 _engine.Connection. Please read fully the notes at :ref:`session_persistence_mapper` for guidelines on using these methods; generally, the .SessionEvents.before_flush method should be preferred for general on-flush changes.

Parameters
mapperthe _orm.Mapper which is the target of this event.
connectionthe _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.
targetthe mapped instance being persisted. If the event is configured with raw=True, this will instead be the .InstanceState state-management object associated with the instance.
Returns
No return value is supported by this event.
def before_configured(self):

Called before a series of mappers have been configured.

The .MapperEvents.before_configured event is invoked each time the _orm.configure_mappers function is invoked, before the function has done any of its work. _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.

This event can only be applied to the _orm.Mapper class or .mapper function, and not to individual mappings or mapped classes. It is only invoked for all mappings as a whole:

from sqlalchemy.orm import mapper

@event.listens_for(mapper, "before_configured")
def go():
    # ...

Contrast this event to .MapperEvents.after_configured, which is invoked after the series of mappers has been configured, as well as .MapperEvents.before_mapper_configured and .MapperEvents.mapper_configured, which are both invoked on a per-mapper basis.

Theoretically this event is called once per application, but is actually called any time new mappers are to be affected by a _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:

from sqlalchemy.orm import mapper

@event.listens_for(mapper, "before_configured", once=True)
def go():
    # ...
New in version 0.9.3.

See Also

.MapperEvents.before_mapper_configured

.MapperEvents.mapper_configured

.MapperEvents.after_configured

def before_delete(self, mapper, connection, target):

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

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.

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.

Warning

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 _engine.Connection. Please read fully the notes at :ref:`session_persistence_mapper` for guidelines on using these methods; generally, the .SessionEvents.before_flush method should be preferred for general on-flush changes.

Parameters
mapperthe _orm.Mapper which is the target of this event.
connectionthe _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.
targetthe mapped instance being deleted. If the event is configured with raw=True, this will instead be the .InstanceState state-management object associated with the instance.
Returns
No return value is supported by this event.
def before_insert(self, mapper, connection, target):

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

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.

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 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.

Warning

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 _engine.Connection. Please read fully the notes at :ref:`session_persistence_mapper` for guidelines on using these methods; generally, the .SessionEvents.before_flush method should be preferred for general on-flush changes.

Parameters
mapperthe _orm.Mapper which is the target of this event.
connectionthe _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.
targetthe mapped instance being persisted. If the event is configured with raw=True, this will instead be the .InstanceState state-management object associated with the instance.
Returns
No return value is supported by this event.
def before_mapper_configured(self, mapper, class_):

Called right before a specific mapper is to be configured.

This event is intended to allow a specific mapper to be skipped during the configure step, by returning the .orm.interfaces.EXT_SKIP symbol which indicates to the .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 function will continue to be called when mappers are used, to continue to try to configure all available mappers.

In comparison to the other configure-level events, .MapperEvents.before_configured, .MapperEvents.after_configured, and .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.

New in version 1.3.

e.g.:

from sqlalchemy.orm import EXT_SKIP

Base = declarative_base()

DontConfigureBase = declarative_base()

@event.listens_for(
    DontConfigureBase,
    "before_mapper_configured", retval=True, propagate=True)
def dont_configure(mapper, cls):
    return EXT_SKIP

See Also

.MapperEvents.before_configured

.MapperEvents.after_configured

.MapperEvents.mapper_configured

def before_update(self, mapper, connection, target):

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

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.

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 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.

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).

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 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.

Warning

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 _engine.Connection. Please read fully the notes at :ref:`session_persistence_mapper` for guidelines on using these methods; generally, the .SessionEvents.before_flush method should be preferred for general on-flush changes.

Parameters
mapperthe _orm.Mapper which is the target of this event.
connectionthe _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.
targetthe mapped instance being persisted. If the event is configured with raw=True, this will instead be the .InstanceState state-management object associated with the instance.
Returns
No return value is supported by this event.
def instrument_class(self, mapper, class_):

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

This event is the earliest phase of mapper construction. Most attributes of the mapper are not yet initialized.

This listener can either be applied to the _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):

Base = declarative_base()

@event.listens_for(Base, "instrument_class", propagate=True)
def on_new_class(mapper, cls_):
    " ... "
Parameters
mapperthe _orm.Mapper which is the target of this event.
class​_the mapped class.
def mapper_configured(self, mapper, class_):

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

The .MapperEvents.mapper_configured event is invoked for each mapper that is encountered when the _orm.configure_mappers function proceeds through the current list of not-yet-configured mappers. _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.

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 :paramref:`.orm.relationship.back_populates` argument will be fully available, since this style of relationship does not rely upon other possibly-not-configured mappers to know that they exist.

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 event; this event invokes only after all known mappings have been fully configured.

The .MapperEvents.mapper_configured event, unlike .MapperEvents.before_configured or .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.

See Also

.MapperEvents.before_configured

.MapperEvents.after_configured

.MapperEvents.before_mapper_configured

Parameters
mapperthe _orm.Mapper which is the target of this event.
class​_the mapped class.
_target_class_doc: str =

Undocumented