SQLAlchemy 0.5 Documentation - module sqlalchemy.orm

# SQLAlchemy 0.5 Documentation

Multiple Pages | One Page
Version: 0.5.0rc3 Last Updated: 11/07/08 13:55:35

### module sqlalchemy.orm

Functional constructs for ORM configuration.

See the SQLAlchemy object relational tutorial and mapper configuration documentation for an overview of how this module is used.

### Module Functions

def backref(name, **kwargs)

Create a BackRef object with explicit arguments, which are the same arguments one can send to `relation()`.

Used with the backref keyword argument to `relation()` in place of a string argument.

def class_mapper(class_, compile=True)

Given a class (or an object), return the primary Mapper associated with the key.

Raises UnmappedClassError if no mapping is configured.

def clear_mappers()

Remove all mappers that have been created thus far.

The mapped classes will return to their initial "unmapped" state and can be re-mapped with new mappers.

def column_property(*args, **kwargs)

Provide a column-level property for use with a Mapper.

Column-based properties can normally be applied to the mapper's `properties` dictionary using the `schema.Column` element directly. Use this function when the given column is not directly present within the mapper's selectable; examples include SQL expressions, functions, and scalar SELECT queries.

Columns that aren't present in the mapper's selectable won't be persisted by the mapper and are effectively "read-only" attributes.

> *cols
>   list of Column objects to be mapped.
> group
>   a group name for this property when marked as deferred.
> deferred
>   when True, the column property is "deferred", meaning that it does not load immediately, and is instead loaded when the attribute is first accessed on an instance. See also deferred().
> extension
>   an AttributeExtension instance, or list of extensions, which will be prepended to the list of attribute listeners for the resulting descriptor placed on the class. These listeners will receive append and set events before the operation proceeds, and may be used to halt (via exception throw) or change the value used in the operation.

def comparable_property(comparator_factory, descriptor=None)

Provide query semantics for an unmanaged attribute.

Allows a regular Python @property (descriptor) to be used in Queries and SQL constructs like a managed attribute. comparable_property wraps a descriptor with a proxy that directs operator overrides such as == (__eq__) to the supplied comparator but proxies everything else through to the original descriptor:

    class MyClass(object):
        @property
        def myprop(self):
            return 'foo'

    class MyComparator(sqlalchemy.orm.interfaces.PropComparator):
        def __eq__(self, other):
            ....

    mapper(MyClass, mytable, properties=dict(
             'myprop': comparable_property(MyComparator)))

Used with the `properties` dictionary sent to mapper().

comparator_factory
  A PropComparator subclass or factory that defines operator behavior for this property.
descriptor

  Optional when used in a `properties={}` declaration. The Python descriptor or property to layer comparison behavior on top of.

  The like-named descriptor will be automatically retreived from the mapped class if left blank in a `properties` declaration.

def compile_mappers()

Compile all mappers that have been defined.

This is equivalent to calling `compile()` on any individual mapper.

def composite(class_, *cols, **kwargs)

Return a composite column-based property for use with a Mapper.

This is very much like a column-based property except the given class is used to represent "composite" values composed of one or more columns.

The class must implement a constructor with positional arguments matching the order of columns supplied here, as well as a __composite_values__() method which returns values in the same order.

A simple example is representing separate two columns in a table as a single, first-class "Point" object:

    class Point(object):
        def __init__(self, x, y):
            self.x = x
            self.y = y
        def __composite_values__(self):
            return self.x, self.y
        def __eq__(self, other):
            return other is not None and self.x == other.x and self.y == other.y

    # and then in the mapping:
    ... composite(Point, mytable.c.x, mytable.c.y) ...

The composite object may have its attributes populated based on the names of the mapped columns. To override the way internal state is set, additionally implement `__set_composite_values__`:

> class Point(object):
>   def __init__(self, x, y):
>     self.some_x = x self.some_y = y
>   def __composite_values__(self):
>     return self.some_x, self.some_y
>   def __set_composite_values__(self, x, y):
>     self.some_x = x self.some_y = y
>   def __eq__(self, other):
>     return other is not None and self.some_x == other.x and self.some_y == other.y

Arguments are:

class_
  The "composite type" class.
*cols
  List of Column objects to be mapped.
group
  A group name for this property when marked as deferred.
deferred
  When True, the column property is "deferred", meaning that it does not load immediately, and is instead loaded when the attribute is first accessed on an instance. See also deferred().
comparator
  An optional instance of PropComparator which provides SQL expression generation functions for this composite type.
extension
  an AttributeExtension instance, or list of extensions, which will be prepended to the list of attribute listeners for the resulting descriptor placed on the class. These listeners will receive append and set events before the operation proceeds, and may be used to halt (via exception throw) or change the value used in the operation.

def contains_alias(alias)

Return a `MapperOption` that will indicate to the query that the main table has been aliased.

alias is the string name or `Alias` object representing the alias.

def contains_eager(*keys, **kwargs)

Return a `MapperOption` that will indicate to the query that the given attribute will be eagerly loaded.

Used when feeding SQL result sets directly into `query.instances()`. Also bundles an `EagerLazyOption` to turn on eager loading in case it isn't already.

alias is the string name of an alias, or an `sql.Alias` object, which represents the aliased columns in the query. This argument is optional.

def create_session(bind=None, **kwargs)

create a new Session.

The defaults of create_session() are the opposite of that of sessionmaker(); autoflush and expire_on_commit are false, autocommit is True. In this sense the session acts more like the "classic" SQLAlchemy 0.3 session with these defaults.

It is recommended to use the sessionmaker() function instead of create_session().

def defer(*keys)

Return a `MapperOption` that will convert the column property of the given name into a deferred load.

Used with `query.options()`

def deferred(*columns, **kwargs)

Return a `DeferredColumnProperty`, which indicates this object attributes should only be loaded from its corresponding table column when first accessed.

Used with the properties dictionary sent to `mapper()`.

def dynamic_loader(argument, secondary=None, primaryjoin=None, secondaryjoin=None, foreign_keys=None, backref=None, post_update=False, cascade=False, remote_side=None, enable_typechecks=True, passive_deletes=False, order_by=None)

Construct a dynamically-loading mapper property.

This property is similar to relation(), except read operations return an active Query object, which reads from the database in all cases. Items may be appended to the attribute via append(), or removed via remove(); changes will be persisted to the database during a flush(). However, no other list mutation operations are available.

A subset of arguments available to relation() are available here.

def eagerload(*keys)

Return a `MapperOption` that will convert the property of the given name into an eager load.

Used with `query.options()`.

def eagerload_all(*keys)

Return a `MapperOption` that will convert all properties along the given dot-separated path into an eager load.

For example, this:

    query.options(eagerload_all('orders.items.keywords'))...

will set all of 'orders', 'orders.items', and 'orders.items.keywords' to load in one eager load.

Used with `query.options()`.

def extension(ext)

Return a `MapperOption` that will insert the given `MapperExtension` to the beginning of the list of extensions that will be called in the context of the `Query`.

Used with `query.options()`.

def lazyload(*keys)

Return a `MapperOption` that will convert the property of the given name into a lazy load.

Used with `query.options()`.

def mapper(class_, local_table=None, *args, **params)

Return a new Mapper object.

class_
  The class to be mapped.
local_table
  The table to which the class is mapped, or None if this mapper inherits from another mapper using concrete table inheritance.
always_refresh
  If True, all query operations for this mapped class will overwrite all data within object instances that already exist within the session, erasing any in-memory changes with whatever information was loaded from the database. Usage of this flag is highly discouraged; as an alternative, see the method populate_existing() on Query.
allow_column_override
  If True, allows the usage of a `relation()` which has the same name as a column in the mapped table. The table column will no longer be mapped.
allow_null_pks
  Indicates that composite primary keys where one or more (but not all) columns contain NULL is a valid primary key. Primary keys which contain NULL values usually indicate that a result row does not contain an entity and should be skipped.
batch
  Indicates that save operations of multiple entities can be batched together for efficiency. setting to False indicates that an instance will be fully saved before saving the next instance, which includes inserting/updating all table rows corresponding to the entity as well as calling all `MapperExtension` methods corresponding to the save operation.
column_prefix
  A string which will be prepended to the key name of all Columns when creating column-based properties from the given Table. Does not affect explicitly specified column-based properties
concrete
  If True, indicates this mapper should use concrete table inheritance with its parent mapper.
extension
  A MapperExtension instance or list of `MapperExtension` instances which will be applied to all operations by this `Mapper`.
inherits
  Another `Mapper` for which this `Mapper` will have an inheritance relationship with.
inherit_condition
  For joined table inheritance, a SQL expression (constructed `ClauseElement`) which will define how the two tables are joined; defaults to a natural join between the two tables.
inherit_foreign_keys
  when inherit_condition is used and the condition contains no ForeignKey columns, specify the "foreign" columns of the join condition in this list. else leave as None.
order_by
  A single `Column` or list of `Columns` for which selection operations should use as the default ordering for entities. Defaults to the OID/ROWID of the table if any, or the first primary key column of the table.
non_primary
  Construct a `Mapper` that will define only the selection of instances, not their persistence. Any number of non_primary mappers may be created for a particular class.
polymorphic_on
  Used with mappers in an inheritance relationship, a `Column` which will identify the class/mapper combination to be used with a particular row. Requires the `polymorphic_identity` value to be set for all mappers in the inheritance hierarchy. The column specified by `polymorphic_on` is usually a column that resides directly within the base mapper's mapped table; alternatively, it may be a column that is only present within the <selectable> portion of the `with_polymorphic` argument.
_polymorphic_map
  Used internally to propagate the full map of polymorphic identifiers to surrogate mappers.
polymorphic_identity
  A value which will be stored in the Column denoted by polymorphic_on, corresponding to the class identity of this mapper.
polymorphic_fetch
  specifies how subclasses mapped through joined-table inheritance will be fetched. options are 'union', 'select', and 'deferred'. if the 'with_polymorphic' argument is present, defaults to 'union', otherwise defaults to 'select'.
properties
  A dictionary mapping the string names of object attributes to `MapperProperty` instances, which define the persistence behavior of that attribute. Note that the columns in the mapped table are automatically converted into `ColumnProperty` instances based on the key property of each `Column` (although they can be overridden using this dictionary).
include_properties
  An inclusive list of properties to map. Columns present in the mapped table but not present in this list will not be automatically converted into properties.
exclude_properties
  A list of properties not to map. Columns present in the mapped table and present in this list will not be automatically converted into properties. Note that neither this option nor include_properties will allow an end-run around Python inheritance. If mapped class `B` inherits from mapped class `A`, no combination of includes or excludes will allow `B` to have fewer properties than its superclass, `A`.
primary_key
  A list of `Column` objects which define the primary key to be used against this mapper's selectable unit. This is normally simply the primary key of the local_table, but can be overridden here.
with_polymorphic
  A tuple in the form `(<classes>, <selectable>)` indicating the default style of "polymorphic" loading, that is, which tables are queried at once. <classes> is any single or list of mappers and/or classes indicating the inherited classes that should be loaded at once. The special value `'*'` may be used to indicate all descending classes should be loaded immediately. The second tuple argument <selectable> indicates a selectable that will be used to query for multiple classes. Normally, it is left as None, in which case this mapper will form an outer join from the base mapper's table to that of all desired sub-mappers. When specified, it provides the selectable to be used for polymorphic loading. When with_polymorphic includes mappers which load from a "concrete" inheriting table, the <selectable> argument is required, since it usually requires more complex UNION queries.
select_table
  Deprecated. Synonymous with `with_polymorphic=('*', <selectable>)`.
version_id_col
  A `Column` which must have an integer type that will be used to keep a running version id of mapped entities in the database. this is used during save operations to ensure that no other thread or process has updated the instance during the lifetime of the entity, else a `ConcurrentModificationError` exception is thrown.

def noload(*keys)

Return a `MapperOption` that will convert the property of the given name into a non-load.

Used with `query.options()`.

def object_mapper(instance)

Given an object, return the primary Mapper associated with the object instance.

Raises UnmappedInstanceError if no mapping is configured.

def object_session(instance)

Return the `Session` to which instance belongs, or None.

def polymorphic_union(table_map, typecolname, aliasname='p_union')

Create a `UNION` statement used by a polymorphic mapper.

See the SQLAlchemy advanced mapping docs for an example of how this is used.

def reconstructor(fn)

Decorate a method as the 'reconstructor' hook.

Designates a method as the "reconstructor", an `__init__`-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.

def relation(argument, secondary=None, **kwargs)

Provide a relationship of a primary Mapper to a secondary Mapper.

This corresponds to a parent-child or associative table relationship. The constructed class is an instance of PropertyLoader.

> argument
>   a class or Mapper instance, representing the target of the relation.
> secondary
>   for a many-to-many relationship, specifies the intermediary table. The `secondary` keyword argument should generally only be used for a table that is not otherwise expressed in any class mapping. In particular, using the Association Object Pattern is generally mutually exclusive against using the `secondary` keyword argument.

> **kwargs follow:

> > backref
> >   indicates the name of a property to be placed on the related mapper's class that will handle this relationship in the other direction, including synchronizing the object attributes on both sides of the relation. Can also point to a `backref()` construct for more configurability.
> > cascade

> >   a comma-separated list of cascade rules which determines how Session operations should be "cascaded" from parent to child. This defaults to "False", which means the default cascade should be used. The default value is "save-update, merge". Available cascades are:

> >   > save-update - cascade the "add()" operation (formerly known as save() and update())

> >   > merge - cascade the "merge()" operation

> >   > expunge - cascade the "expunge()" operation

> >   > delete - cascade the "delete()" operation

> >   > delete-orphan - if an item of the child's type with no parent is detected, mark it for deletion. Note that this option prevents a pending item of the child's class from being persisted without a parent present.

> >   > refresh-expire - cascade the expire() and refresh() operations

> >   > all - shorthand for "save-update,merge, refresh-expire, expunge, delete"

> > collection_class
> >   a class or function that returns a new list-holding object. will be used in place of a plain list for storing elements.
> > extension
> >   an AttributeExtension instance, or list of extensions, which will be prepended to the list of attribute listeners for the resulting descriptor placed on the class. These listeners will receive append and set events before the operation proceeds, and may be used to halt (via exception throw) or change the value used in the operation.
> > foreign_keys
> >   a list of columns which are to be used as "foreign key" columns. this parameter should be used in conjunction with explicit `primaryjoin` and `secondaryjoin` (if needed) arguments, and the columns within the `foreign_keys` list should be present within those join conditions. Normally, `relation()` will inspect the columns within the join conditions to determine which columns are the "foreign key" columns, based on information in the `Table` metadata. Use this argument when no ForeignKey's are present in the join condition, or to override the table-defined foreign keys.
> > join_depth=None
> >   when non-`None`, an integer value indicating how many levels deep eagerload joins should be constructed on a self-referring or cyclical relationship. The number counts how many times the same Mapper shall be present in the loading condition along a particular join branch. When left at its default of `None`, eager loads will automatically stop chaining joins when they encounter a mapper which is already higher up in the chain.
> > lazy=(True|False|None|'dynamic')

> >   specifies how the related items should be loaded. Values include:

> >   > True - items should be loaded lazily when the property is first
> >   >   accessed.
> >   > False - items should be loaded "eagerly" in the same query as that
> >   >   of the parent, using a JOIN or LEFT OUTER JOIN.
> >   > None - no loading should occur at any time. This is to support
> >   >   "write-only" attributes, or attributes which are populated in some manner specific to the application.
> >   > 'dynamic' - a `DynaLoader` will be attached, which returns a
> >   >   `Query` object for all read operations. The dynamic- collection supports only `append()` and `remove()` for write operations; changes to the dynamic property will not be visible until the data is flushed to the database.

> > order_by
> >   indicates the ordering that should be applied when loading these items.
> > passive_deletes=False

> >   Indicates loading behavior during delete operations.

> >   A value of True indicates that unloaded child items should not be loaded during a delete operation on the parent. Normally, when a parent item is deleted, all child items are loaded so that they can either be marked as deleted, or have their foreign key to the parent set to NULL. Marking this flag as True usually implies an ON DELETE <CASCADE|SET NULL> rule is in place which will handle updating/deleting child rows on the database side.

> >   Additionally, setting the flag to the string value 'all' will disable the "nulling out" of the child foreign keys, when there is no delete or delete-orphan cascade enabled. This is typically used when a triggering or error raise scenario is in place on the database side. Note that the foreign key attributes on in-session child objects will not be changed after a flush occurs so this is a very special use-case setting.

> > passive_updates=True

> >   Indicates loading and INSERT/UPDATE/DELETE behavior when the source of a foreign key value changes (i.e. an "on update" cascade), which are typically the primary key columns of the source row.

> >   When True, it is assumed that ON UPDATE CASCADE is configured on the foreign key in the database, and that the database will handle propagation of an UPDATE from a source column to dependent rows. Note that with databases which enforce referential integrity (i.e. Postgres, MySQL with InnoDB tables), ON UPDATE CASCADE is required for this operation. The relation() will update the value of the attribute on related items which are locally present in the session during a flush.

> >   When False, it is assumed that the database does not enforce referential integrity and will not be issuing its own CASCADE operation for an update. The relation() will issue the appropriate UPDATE statements to the database in response to the change of a referenced key, and items locally present in the session during a flush will also be refreshed.

> >   This flag should probably be set to False if primary key changes are expected and the database in use doesn't support CASCADE (i.e. SQLite, MySQL MyISAM tables).

> > post_update
> >   this indicates that the relationship should be handled by a second UPDATE statement after an INSERT or before a DELETE. Currently, it also will issue an UPDATE after the instance was UPDATEd as well, although this technically should be improved. This flag is used to handle saving bi-directional dependencies between two individual rows (i.e. each row references the other), where it would otherwise be impossible to INSERT or DELETE both rows fully since one row exists before the other. Use this flag when a particular mapping arrangement will incur two rows that are dependent on each other, such as a table that has a one-to-many relationship to a set of child rows, and also has a column that references a single child row within that list (i.e. both tables contain a foreign key to each other). If a `flush()` operation returns an error that a "cyclical dependency" was detected, this is a cue that you might want to use `post_update` to "break" the cycle.
> > primaryjoin
> >   a ClauseElement that will be used as the primary join of this child object against the parent object, or in a many-to-many relationship the join of the primary object to the association table. By default, this value is computed based on the foreign key relationships of the parent and child tables (or association table).
> > remote_side
> >   used for self-referential relationships, indicates the column or list of columns that form the "remote side" of the relationship.
> > secondaryjoin
> >   a ClauseElement that will be used as the join of an association table to the child object. By default, this value is computed based on the foreign key relationships of the association and child tables.
> > uselist=(True|False)
> >   a boolean that indicates if this property should be loaded as a list or a scalar. In most cases, this value is determined automatically by `relation()`, based on the type and direction of the relationship - one to many forms a list, many to one forms a scalar, many to many is a list. If a scalar is desired where normally a list would be present, such as a bi-directional one-to-one relationship, set uselist to False.
> > viewonly=False
> >   when set to True, the relation is used only for loading objects within the relationship, and has no effect on the unit-of-work flush process. Relations with viewonly can specify any kind of join conditions to provide additional views of related objects onto a parent object. Note that the functionality of a viewonly relationship has its limits - complicated join conditions may not compile into eager or lazy loaders properly. If this is the case, use an alternative method.

def scoped_session(session_factory, scopefunc=None)

Provides thread-local management of Sessions.

This is a front-end function to the ScopedSession class.

Usage:

    Session = scoped_session(sessionmaker(autoflush=True))

To instantiate a Session object which is part of the scoped context, instantiate normally:

    session = Session()

Most session methods are available as classmethods from the scoped session:

    Session.commit()
    Session.close()

To map classes so that new instances are saved in the current Session automatically, as well as to provide session-aware class attributes such as "query", use the mapper classmethod from the scoped session:

    mapper = Session.mapper
    mapper(Class, table, ...)

def sessionmaker(bind=None, class_=None, autoflush=True, autocommit=False, expire_on_commit=True, **kwargs)

Generate a custom-configured Session class.

The returned object is a subclass of `Session`, which, when instantiated with no arguments, uses the keyword arguments configured here as its constructor arguments.

It is intended that the sessionmaker() function be called within the global scope of an application, and the returned class be made available to the rest of the application as the single class used to instantiate sessions.

e.g.:

    # global scope
    Session = sessionmaker(autoflush=False)

    # later, in a local scope, create and use a session:
    sess = Session()

Any keyword arguments sent to the constructor itself will override the "configured" keywords:

    Session = sessionmaker()

    # bind an individual session to a connection
    sess = Session(bind=connection)

The class also includes a special classmethod `configure()`, which allows additional configurational options to take place after the custom `Session` class has been generated. This is useful particularly for defining the specific `Engine` (or engines) to which new instances of `Session` should be bound:

    Session = sessionmaker()
    Session.configure(bind=create_engine('sqlite:///foo.db'))

    sess = Session()

Options:

autocommit

  Defaults to `False`. When `True`, the `Session` does not keep a persistent transaction running, and will acquire connections from the engine on an as-needed basis, returning them immediately after their use. Flushes will begin and commit (or possibly rollback) their own transaction if no transaction is present. When using this mode, the session.begin() method may be used to begin a transaction explicitly.

  Leaving it on its default value of `False` means that the `Session` will acquire a connection and begin a transaction the first time it is used, which it will maintain persistently until `rollback()`, `commit()`, or `close()` is called. When the transaction is released by any of these methods, the `Session` is ready for the next usage, which will again acquire and maintain a new connection/transaction.

expire_on_commit
  Defaults to `True`. When `True`, all instances will be fully expired after each `commit()`, so that all attribute/object access subsequent to a completed transaction will load from the most recent database state.
_enable_transaction_accounting
  Defaults to `True`. A legacy-only flag which when `False` disables all 0.5-style object accounting on transaction boundaries, including auto-expiry of instances on rollback and commit, maintenance of the "new" and "deleted" lists upon rollback, and autoflush of pending changes upon begin(), all of which are interdependent.
autoflush
  When `True`, all query operations will issue a `flush()` call to this `Session` before proceeding. This is a convenience feature so that `flush()` need not be called repeatedly in order for database queries to retrieve results. It's typical that `autoflush` is used in conjunction with `autocommit=False`. In this scenario, explicit calls to `flush()` are rarely needed; you usually only need to call `commit()` (which flushes) to finalize changes.
bind
  An optional `Engine` or `Connection` to which this `Session` should be bound. When specified, all SQL operations performed by this session will execute via this connectable.
binds

  An optional dictionary, which contains more granular "bind" information than the `bind` parameter provides. This dictionary can map individual `Table` instances as well as `Mapper` instances to individual `Engine` or `Connection` objects. Operations which proceed relative to a particular `Mapper` will consult this dictionary for the direct `Mapper` instance as well as the mapper's `mapped_table` attribute in order to locate an connectable to use. The full resolution is described in the `get_bind()` method of `Session`. Usage looks like:

      sess = Session(binds={
          SomeMappedClass: create_engine('postgres://engine1'),
          somemapper: create_engine('postgres://engine2'),
          some_table: create_engine('postgres://engine3'),
          })

  Also see the `bind_mapper()` and `bind_table()` methods.

class_
  Specify an alternate class other than `sqlalchemy.orm.session.Session` which should be used by the returned class. This is the only argument that is local to the `sessionmaker()` function, and is not sent directly to the constructor for `Session`.
echo_uow
  Deprecated. Use `logging.getLogger('sqlalchemy.orm.unitofwork').setLevel(logging.DEBUG)`.
extension
  An optional SessionExtension instance, or a list of such instances, which will receive pre- and post- commit and flush events, as well as a post-rollback event. User- defined code may be placed within these hooks using a user-defined subclass of `SessionExtension`.
twophase
  When `True`, all transactions will be started using [sqlalchemy.engine_TwoPhaseTransaction]. During a `commit()`, after `flush()` has been issued for all attached databases, the `prepare()` method on each database's `TwoPhaseTransaction` will be called. This allows each database to roll back the entire transaction, before each transaction is committed.
query_cls
  Class which should be used to create new Query objects, as returned by the `query()` method. Defaults to Query.
weak_identity_map
  When set to the default value of `False`, a weak-referencing map is used; instances which are not externally referenced will be garbage collected immediately. For dereferenced instances which have pending changes present, the attribute management system will create a temporary strong-reference to the object which lasts until the changes are flushed to the database, at which point it's again dereferenced. Alternatively, when using the value `True`, the identity map uses a regular Python dictionary to store instances. The session will maintain all instances present until they are removed using expunge(), clear(), or purge().

def synonym(name, map_column=False, descriptor=None, comparator_factory=None, proxy=False)

Set up name as a synonym to another mapped property.

Used with the `properties` dictionary sent to mapper().

Any existing attributes on the class which map the key name sent to the `properties` dictionary will be used by the synonym to provide instance-attribute behavior (that is, any Python property object, provided by the `property` builtin or providing a `__get__()`, `__set__()` and `__del__()` method). If no name exists for the key, the `synonym()` creates a default getter/setter object automatically and applies it to the class.

name refers to the name of the existing mapped property, which can be any other `MapperProperty` including column-based properties and relations.

If map_column is `True`, an additional `ColumnProperty` is created on the mapper automatically, using the synonym's name as the keyname of the property, and the keyname of this `synonym()` as the name of the column to map. For example, if a table has a column named `status`:

    class MyClass(object):
        def _get_status(self):
            return self._status
        def _set_status(self, value):
            self._status = value
        status = property(_get_status, _set_status)

    mapper(MyClass, sometable, properties={
        "status":synonym("_status", map_column=True)
    })

The column named `status` will be mapped to the attribute named `_status`, and the `status` attribute on `MyClass` will be used to proxy access to the column-based attribute.

The proxy keyword argument is deprecated and currently does nothing; synonyms now always establish an attribute getter/setter function if one is not already available.

def undefer(*keys)

Return a `MapperOption` that will convert the column property of the given name into a non-deferred (regular column) load.

Used with `query.options()`.

def undefer_group(name)

Return a `MapperOption` that will convert the given group of deferred column properties into a non-deferred (regular column) load.

Used with `query.options()`.

def validates(*names)

Decorate a method as a 'validator' for one or more named properties.

Designates a method as a validator, a method which receives the name of the attribute as well as a value to be assigned, or in the case of a collection to be added to the collection. The function can then raise validation exceptions to halt the process from continuing, or can modify or replace the value before proceeding. The function should otherwise return the given value.

### class AliasedClass(object)

Represents an 'alias'ed form of a mapped class for usage with Query.

The ORM equivalent of a sqlalchemy.sql.expression.Alias object, this object mimics the mapped class using a __getattr__ scheme and maintains a reference to a real Alias object. It indicates to Query that the selectable produced for this class should be aliased, and also adapts PropComparators produced by the class' InstrumentedAttributes so that they adapt the "local" side of SQL expressions against the alias.

def __init__(self, cls, alias=None, name=None)

Construct a new `AliasedClass`.

def __getattr__(self, key)
back to section top

### class InstrumentationManager(object)

User-defined class instrumentation extension.

def __init__(self, class_)

Construct a new `InstrumentationManager`.

def dispose(self, class_, manager)
def get_instance_dict(self, class_, instance)
def initialize_instance_dict(self, class_, instance)
def install_descriptor(self, class_, key, inst)
def install_member(self, class_, key, implementation)
def install_state(self, class_, instance, state)
def instrument_attribute(self, class_, key, inst)
def instrument_collection_class(self, class_, key, collection_class)
def manage(self, class_, manager)
def manager_getter(self, class_)
def state_getter(self, class_)
def uninstall_descriptor(self, class_, key)
def uninstall_member(self, class_, key)
back to section top

### class MapperExtension(object)

Base implementation for customizing Mapper behavior.

For each method in MapperExtension, returning a result of EXT_CONTINUE will allow processing to continue to the next MapperExtension in line or use the default functionality if there are no other extensions.

Returning EXT_STOP will halt processing of further extensions handling that method. Some methods such as `load` have other return requirements, see the individual documentation for details. Other than these exception cases, any return value other than EXT_CONTINUE or EXT_STOP will be interpreted as equivalent to EXT_STOP.

def after_delete(self, mapper, connection, instance)

Receive an object instance after that instance is DELETEed.

def after_insert(self, mapper, connection, instance)

Receive an object instance after that instance is INSERTed.

def after_update(self, mapper, connection, instance)

Receive an object instance after that instance is UPDATEed.

def append_result(self, mapper, selectcontext, row, instance, result, **flags)

Receive an object instance before that instance is appended to a result list.

If this method returns EXT_CONTINUE, result appending will proceed normally. if this method returns any other value or None, result appending will not proceed for this instance, giving this extension an opportunity to do the appending itself, if desired.

mapper
  The mapper doing the operation.
selectcontext
  SelectionContext corresponding to the instances() call.
row
  The result row from the database.
instance
  The object instance to be appended to the result.
result
  List to which results are being appended.
**flags
  extra information about the row, same as criterion in `create_row_processor()` method of MapperProperty

def before_delete(self, mapper, connection, instance)

Receive an object instance before that instance is DELETEed.

Note that no changes to the overall flush plan can be made here; this means any collection modification, save() or delete() operations which occur within this method will not take effect until the next flush call.

def before_insert(self, mapper, connection, instance)

Receive an object instance before that instance is INSERTed into its table.

This is a good place to set up primary key values and such that aren't handled otherwise.

Column-based attributes can be modified within this method which will result in the new value being inserted. However no changes to the overall flush plan can be made; this means any collection modification or save() operations which occur within this method will not take effect until the next flush call.

def before_update(self, mapper, connection, instance)

Receive an object instance before that instance is UPDATEed.

Note that 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 before_update is not a guarantee that an UPDATE statement will be issued (although you can affect the outcome here).

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

Column-based attributes can be modified within this method which will result in their being updated. However no changes to the overall flush plan can be made; this means any collection modification or save() operations which occur within this method will not take effect until the next flush call.

def create_instance(self, mapper, selectcontext, row, class_)

Receive a row when a new object instance is about to be created from that row.

The method can choose to create the instance itself, or it can return EXT_CONTINUE to indicate normal object creation should take place.

mapper
  The mapper doing the operation
selectcontext
  SelectionContext corresponding to the instances() call
row
  The result row from the database
class_
  The class we are mapping.
return value
  A new object instance, or EXT_CONTINUE

def init_failed(self, mapper, class_, oldinit, instance, args, kwargs)
def init_instance(self, mapper, class_, oldinit, instance, args, kwargs)
def instrument_class(self, mapper, class_)
def populate_instance(self, mapper, selectcontext, row, instance, **flags)

Receive an instance before that instance has its attributes populated.

This usually corresponds to a newly loaded instance but may also correspond to an already-loaded instance which has unloaded attributes to be populated. The method may be called many times for a single instance, as multiple result rows are used to populate eagerly loaded collections.

If this method returns EXT_CONTINUE, instance population will proceed normally. If any other value or None is returned, instance population will not proceed, giving this extension an opportunity to populate the instance itself, if desired.

As of 0.5, most usages of this hook are obsolete. For a generic "object has been newly created from a row" hook, use `reconstruct_instance()`, or the `@orm.reconstructor` decorator.

def reconstruct_instance(self, mapper, instance)

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

This typicically occurs when the instance is created based on incoming result rows, and is only called once for that instance's lifetime.

Note that during a result-row load, this method is called upon the first row received for this instance. If eager loaders are set to further populate collections on the instance, those will not yet be completely loaded.

def translate_row(self, mapper, context, row)

Perform pre-processing on the given result row and return a new row instance.

This is called when the mapper first receives a row, before the object identity or the instance itself has been derived from that row.

back to section top

### class PropComparator(ColumnOperators)

defines comparison operations for MapperProperty objects.

PropComparator instances should also define an accessor 'property' which returns the MapperProperty associated with this PropComparator.

def __init__(self, prop, mapper, adapter=None)

Construct a new `PropComparator`.

def adapted(self, adapter)

Return a copy of this PropComparator which will use the given adaption function on the local side of generated expressions.

def any(self, criterion=None, **kwargs)

Return true if this collection contains any member that meets the given criterion.

criterion
  an optional ClauseElement formulated against the member class' table or attributes.
**kwargs
  key/value pairs corresponding to member class attribute names which will be compared via equality to the corresponding values.

def has(self, criterion=None, **kwargs)

Return true if this element references a member which meets the given criterion.

criterion
  an optional ClauseElement formulated against the member class' table or attributes.
**kwargs
  key/value pairs corresponding to member class attribute names which will be compared via equality to the corresponding values.

def of_type(self, class_)

Redefine this object in terms of a polymorphic subclass.

Returns a new PropComparator from which further criterion can be evaluated.

e.g.:

    query.join(Company.employees.of_type(Engineer)).\
       filter(Engineer.name=='foo')

class_
  a class or mapper indicating that criterion will be against this specific subclass.

def __clause_element__(self)
back to section top

### class Query(object)

Encapsulates the object-fetching operations provided by Mappers.

def __init__(self, entities, session=None)

Construct a new `Query`.

def add_column(self, column)

Add a SQL ColumnElement to the list of result columns to be returned.

def add_entity(self, entity, alias=None)

add a mapped entity to the list of result columns to be returned.

def all(self)

Return the results represented by this `Query` as a list.

This results in an execution of the underlying query.

def autoflush(self, setting)

Return a Query with a specific 'autoflush' setting.

Note that a Session with autoflush=False will not autoflush, even if this flag is set to True at the Query level. Therefore this flag is usually used only to disable autoflush for a specific Query.

def correlate(self, *args)
def count(self)

Apply this query's criterion to a SELECT COUNT statement.

def delete(self, synchronize_session='fetch')

Perform a bulk delete query.

Deletes rows matched by this query from the database. The synchronize_session parameter chooses the strategy for the removal of matched objects from the session. Valid values are:

False
  don't synchronize the session. Use this when you don't need to use the session after the delete or you can be sure that none of the matched objects are in the session. The behavior of deleted objects still in the session is undefined.
'fetch'
  performs a select query before the delete to find objects that are matched by the delete query and need to be removed from the session. Matched objects are removed from the session. 'fetch' is the default strategy.
'evaluate'

  experimental feature. Tries to evaluate the querys criteria in Python straight on the objects in the session. If evaluation of the criteria isn't implemented, the 'fetch' strategy will be used as a fallback.

  The expression evaluator currently doesn't account for differing string collations between the database and Python.

Returns the number of rows deleted, excluding any cascades.

Warning - this currently doesn't account for any foreign key/relation cascades.

def distinct(self)

Apply a `DISTINCT` to the query and return the newly resulting `Query`.

def filter(self, criterion)

apply the given filtering criterion to the query and return the newly resulting `Query`

the criterion is any sql.ClauseElement applicable to the WHERE clause of a select.

def filter_by(self, **kwargs)

apply the given filtering criterion to the query and return the newly resulting `Query`.

def first(self)

Return the first result of this `Query` or None if the result doesn't contain any row.

This results in an execution of the underlying query.

def from_self(self, *entities)

return a Query that selects from this Query's SELECT statement.

*entities - optional list of entities which will replace those being selected.

def from_statement(self, statement)

Execute the given SELECT statement and return results.

This method bypasses all internal statement compilation, and the statement is executed without modification.

The statement argument is either a string, a `select()` construct, or a `text()` construct, and should return the set of columns appropriate to the entity class represented by this `Query`.

Also see the `instances()` method.

def get(self, ident)

Return an instance of the object based on the given identifier, or None if not found.

The ident argument is a scalar or tuple of primary key column values in the order of the table def's primary key columns.

def group_by(self, *criterion)

apply one or more GROUP BY criterion to the query and return the newly resulting `Query`

def having(self, criterion)

apply a HAVING criterion to the query and return the newly resulting `Query`.

def instances(self, cursor, _Query__context=None)

Given a ResultProxy cursor as returned by connection.execute(), return an ORM result as an iterator.

e.g.:

    result = engine.execute("select * from users")
    for u in session.query(User).instances(result):
        print u

def iterate_instances(self, cursor, _Query__context=None)

Given a ResultProxy cursor as returned by connection.execute(), return an ORM result as an iterator.

Deprecated.

e.g.:

    result = engine.execute("select * from users")
    for u in session.query(User).instances(result):
        print u

def join(self, *props, **kwargs)

Create a join against this `Query` object's criterion and apply generatively, returning the newly resulting `Query`.

Each element in *props may be:

> - a string property name, i.e. "rooms". This will join along the relation of the same name from this Query's "primary" mapper, if one is present.
> - a class-mapped attribute, i.e. Houses.rooms. This will create a join from "Houses" table to that of the "rooms" relation.
> - a 2-tuple containing a target class or selectable, and an "ON" clause. The ON clause can be the property name/ attribute like above, or a SQL expression.

e.g.:

    # join along string attribute names
    session.query(Company).join('employees')
    session.query(Company).join('employees', 'tasks')

    # join the Person entity to an alias of itself,
    # along the "friends" relation
    PAlias = aliased(Person)
    session.query(Person).join((Palias, Person.friends))

    # join from Houses to the "rooms" attribute on the
    # "Colonials" subclass of Houses, then join to the
    # "closets" relation on Room
    session.query(Houses).join(Colonials.rooms, Room.closets)

    # join from Company entities to the "employees" collection,
    # using "people JOIN engineers" as the target.  Then join
    # to the "computers" collection on the Engineer entity.
    session.query(Company).join((people.join(engineers), 'employees'), Engineer.computers)

    # join from Articles to Keywords, using the "keywords" attribute.
    # assume this is a many-to-many relation.
    session.query(Article).join(Article.keywords)

    # same thing, but spelled out entirely explicitly
    # including the association table.
    session.query(Article).join(
        (article_keywords, Articles.id==article_keywords.c.article_id),
        (Keyword, Keyword.id==article_keywords.c.keyword_id)
        )

**kwargs include:

> aliased - when joining, create anonymous aliases of each table. This is used for self-referential joins or multiple joins to the same table. Consider usage of the aliased(SomeClass) construct as a more explicit approach to this.

> from_joinpoint - when joins are specified using string property names, locate the property from the mapper found in the most recent previous join() call, instead of from the root entity.

def limit(self, limit)

Apply a `LIMIT` to the query and return the newly resulting

`Query`.

def offset(self, offset)

Apply an `OFFSET` to the query and return the newly resulting `Query`.

def one(self)

Return exactly one result or raise an exception.

Raises `sqlalchemy.orm.exc.NoResultFound` if the query selects no rows. Raises `sqlalchemy.orm.exc.MultipleResultsFound` if multiple rows are selected.

This results in an execution of the underlying query.

def options(self, *args)

Return a new Query object, applying the given list of MapperOptions.

def order_by(self, *criterion)

apply one or more ORDER BY criterion to the query and return the newly resulting `Query`

def outerjoin(self, *props, **kwargs)

Create a left outer join against this `Query` object's criterion and apply generatively, retunring the newly resulting `Query`.

Usage is the same as the `join()` method.

def params(self, *args, **kwargs)

add values for bind parameters which may have been specified in filter().

parameters may be specified using **kwargs, or optionally a single dictionary as the first positional argument. The reason for both is that **kwargs is convenient, however some parameter dictionaries contain unicode keys in which case **kwargs cannot be used.

def populate_existing(self)

Return a Query that will refresh all instances loaded.

This includes all entities accessed from the database, including secondary entities, eagerly-loaded collection items.

All changes present on entities which are already present in the session will be reset and the entities will all be marked "clean".

An alternative to populate_existing() is to expire the Session fully using session.expire_all().

def query_from_parent(cls, instance, property, **kwargs)

Return a new Query with criterion corresponding to a parent instance.

Deprecated. Use sqlalchemy.orm.with_parent in conjunction with filter().

Return a newly constructed Query object, with criterion corresponding to a relationship to the given parent instance.

instance

  > a persistent or detached instance which is related to class represented by this query.

  property
    string name of the property which relates this query's class to the instance.
  **kwargs
    all extra keyword arguments are propagated to the constructor of Query.

def reset_joinpoint(self)

return a new Query reset the 'joinpoint' of this Query reset back to the starting mapper. Subsequent generative calls will be constructed from the new joinpoint.

Note that each call to join() or outerjoin() also starts from the root.

def scalar(self)

Return the first element of the first result or None.

>     >>> session.query(Item).scalar()
>     <Item>
>     >>> session.query(Item.id).scalar()
>     1
>     >>> session.query(Item.id).filter(Item.id < 0).scalar()
>     None
>     >>> session.query(Item.id, Item.name).scalar()
>     1
>     >>> session.query(func.count(Parent.id)).scalar()
>     20

This results in an execution of the underlying query.

def select_from(self, from_obj)

Set the from_obj parameter of the query and return the newly resulting `Query`. This replaces the table which this Query selects from with the given table.

from_obj is a single table or selectable.

def slice(self, start, stop)

apply LIMIT/OFFSET to the `Query` based on a range and return the newly resulting `Query`.

statement = property()

The full SELECT statement represented by this Query.

def subquery(self)

return the full SELECT statement represented by this Query, embedded within an Alias.

def update(self, values, synchronize_session='expire')

Perform a bulk update query.

Updates rows matched by this query in the database. The values parameter takes a dictionary with object attributes as keys and literal values or sql expressions as values. The synchronize_session parameter chooses the strategy to update the attributes on objects in the session. Valid values are:

False
  don't synchronize the session. Use this when you don't need to use the session after the update or you can be sure that none of the matched objects are in the session.
'expire'
  performs a select query before the update to find objects that are matched by the update query. The updated attributes are expired on matched objects.
'evaluate'

  experimental feature. Tries to evaluate the querys criteria in Python straight on the objects in the session. If evaluation of the criteria isn't implemented, the 'expire' strategy will be used as a fallback.

  The expression evaluator currently doesn't account for differing string collations between the database and Python.

Returns the number of rows matched by the update.

Warning - this currently doesn't account for any foreign key/relation cascades.

def value(self, column)

Return a scalar result corresponding to the given column expression.

def values(self, *columns)

Return an iterator yielding result tuples corresponding to the given list of columns

whereclause = property()

The WHERE criterion for this Query.

def with_labels(self)

Apply column labels to the return value of Query.statement.

Indicates that this Query's statement accessor should return a SELECT statement that applies labels to all columns in the form <tablename>_<columnname>; this is commonly used to disambiguate columns from multiple tables which have the same name.

When the Query actually issues SQL to load rows, it always uses column labeling.

def with_lockmode(self, mode)

Return a new Query object with the specified locking mode.

def with_parent(self, instance, property=None)

Add a join criterion corresponding to a relationship to the given parent instance.

instance
  a persistent or detached instance which is related to class represented by this query.
property
  string name of the property which relates this query's class to the instance. if None, the method will attempt to find a suitable property.

Currently, this method only works with immediate parent relationships, but in the future may be enhanced to work across a chain of parent mappers.

def with_polymorphic(self, cls_or_mappers, selectable=None)

Load columns for descendant mappers of this Query's mapper.

Using this method will ensure that each descendant mapper's tables are included in the FROM clause, and will allow filter() criterion to be used against those tables. The resulting instances will also have those columns already loaded so that no "post fetch" of those columns will be required.

`cls_or_mappers` is a single class or mapper, or list of class/mappers, which inherit from this Query's mapper. Alternatively, it may also be the string `'*'`, in which case all descending mappers will be added to the FROM clause.

`selectable` is a table or select() statement that will be used in place of the generated FROM clause. This argument is required if any of the desired mappers use concrete table inheritance, since SQLAlchemy currently cannot generate UNIONs among tables automatically. If used, the `selectable` argument must represent the full set of tables and columns mapped by every desired mapper. Otherwise, the unaccounted mapped columns will result in their table being appended directly to the FROM clause which will usually lead to incorrect results.

def yield_per(self, count)

Yield only `count` rows at a time.

WARNING: use this method with caution; if the same instance is present in more than one batch of rows, end-user changes to attributes will be overwritten.

In particular, it's usually impossible to use this setting with eagerly loaded collections (i.e. any lazy=False) since those collections will be cleared for a new load when encountered in a subsequent result batch.

def __getitem__(self, item)
def __iter__(self)
back to section top

### class Validator(AttributeExtension)

Runs a validation method on an attribute value to be set or appended.

def __init__(self, key, validator)

Construct a new Validator.

key - name of the attribute to be validated; will be passed as the second argument to the validation method (the first is the object instance itself).

validator - an function or instance method which accepts three arguments; an instance (usually just 'self' for a method), the key name of the attribute, and the value. The function should return the same value given, unless it wishes to modify it.

def append(self, state, value, initiator)
def set(self, state, value, oldvalue, initiator)
back to section top