Constructors and Object Initialization

    The SQLAlchemy ORM does not call __init__ when recreating objects from database rows. The ORM’s process is somewhat akin to the Python standard library’s pickle module, invoking the low level __new__ method and then quietly restoring attributes directly on the instance rather than calling __init__.

    If you need to do some setup on database-loaded instances before they’re ready to use, there is an event hook known as InstanceEvents.load() which can achieve this; it is also available via a class-specific decorator called . When using , the mapper will invoke the decorated method with no arguments every time it loads or reconstructs an instance of the class. This is useful for recreating transient properties that are normally assigned in __init__:

    Above, when obj = MyMappedClass() is executed, the __init__ constructor is invoked normally and the data argument is required. When instances are loaded during a Query operation as in query(MyMappedClass).one(), is called.

    Any method may be tagged as the , even the __init__ method itself. It is invoked after all immediate column-level attributes are loaded as well as after eagerly-loaded scalar relationships. Eagerly loaded collections may be only partially populated or not populated at all, depending on the kind of eager loading used.

    reconstructor() is a shortcut into a larger system of “instance level” events, which can be subscribed to using the event API - see for the full API description of these events.

    function sqlalchemy.orm.``reconstructor(fn)

    Designates a method as the “reconstructor”, an -like method that will be called by the ORM after the instance has been loaded from the database or otherwise reconstituted.

    The reconstructor will be invoked with no arguments. Scalar (non-collection) database-mapped attributes of the instance will be available for use within the function. Eagerly-loaded collections are generally not yet available and will usually only contain the first element. ORM state changes made to objects at this stage will not be recorded for the next flush() operation, so the activity within a reconstructor should be conservative.

    See also

    Constructors and Object Initialization