SQLAlchemy 0.4 Documentation

Multiple Pages | One Page
Version: 0.4.2b Last Updated: 01/07/08 15:05:25

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_, entity_name=None, compile=True)

Given a class and optional entity_name, return the primary Mapper associated with the key.

If no mapper can be located, raises InvalidRequestError.

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

# and then in the mapping:
... composite(Point, mytable.c.x, mytable.c.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.
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(key, alias=None, decorator=None)

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

decorator is mutually exclusive of alias and is a row-processing function which will be applied to the incoming row before sending to the eager load handler. use this for more sophisticated row adjustments beyond a straight alias.

def create_session(bind=None, **kwargs)

create a new Session.

The session by default does not begin a transaction, and requires that flush() be called explicitly in order to persist results to the database.

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

def defer(name)

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, entity_name=None, foreign_keys=None, backref=None, post_update=False, cascade=None, remote_side=None, enable_typechecks=True, passive_deletes=False)

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(name, mapper=None)

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

Used with query.options().

def eagerload_all(name, mapper=None)

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(name, mapper=None)

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.
entity_name
A name to be associated with the class, to allow alternate mappings for a single class.
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.
_polymorphic_map
Used internally to propigate 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 select_table 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.
select_table
A Table or any Selectable which will be used to select instances of this mapper's class. usually used to provide polymorphic loading among several classes in an inheritance hierarchy.
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(name)

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

Used with query.options().

def object_mapper(object, entity_name=None, raiseerror=True)

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

object
The object instance.
entity_name
Entity name of the mapper to retrieve, if the given instance is transient. Otherwise uses the entity name already associated with the instance.
raiseerror
Defaults to True: raise an InvalidRequestError if no mapper can be located. If False, return None.
def object_session(instance)

Return the Session to which the given instance is bound, or None if 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 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:

association
Deprecated; as of version 0.3.0 the association keyword is synonomous with applying the "all, delete-orphan" cascade to a "one-to-many" relationship. SA can now automatically reconcile a "delete" and "insert" operation of two objects with the same "identity" in a flush() operation into a single "update" statement, which is the pattern that "association" used to indicate.
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 string list of cascade rules which determines how persistence operations should be "cascaded" from parent to child.
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.
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.
foreignkey
deprecated. use the foreign_keys argument for foreign key specification, or remote_side for "directional" logic.
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" attrbitutes, 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 (ie. 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).
private=False
deprecated. setting private=True is the equivalent of setting cascade="all, delete-orphan", and indicates the lifecycle of child objects should be contained within that of the parent.
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, transactional=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()

The function features a single keyword argument of its own, class_, which may be used to specify an alternate class other than sqlalchemy.orm.session.Session which should be used by the returned class. All other keyword arguments sent to sessionmaker() are passed through to the instantiated Session() object.

def synonym(name, map_column=False, 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 funciton if one is not already available.

def undefer(name)

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

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.

EXT_PASS is a synonym for EXT_CONTINUE and is provided for backward compatibility.

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 None 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.
def get(self, query, *args, **kwargs)

Override the get method of the Query object.

The return value of this method is used as the result of query.get() if the value is anything other than EXT_CONTINUE.

def get_by(self, query, *args, **kwargs)

Override the get_by method of the Query object.

The return value of this method is used as the result of query.get_by() if the value is anything other than EXT_CONTINUE.

DEPRECATED.

def get_session(self)

Retrieve a contextual Session instance with which to register a new object.

Note: this is not called if a session is provided with the __init__ params (i.e. _sa_session).

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 load(self, query, *args, **kwargs)

Override the load method of the Query object.

The return value of this method is used as the result of query.load() if the value is anything other than EXT_CONTINUE.

def populate_instance(self, mapper, selectcontext, row, instance, **flags)

Receive a newly-created instance before that instance has its attributes populated.

The normal population of attributes is according to each attribute's corresponding MapperProperty (which includes column-based attributes as well as relationships to other classes). 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.

def select(self, query, *args, **kwargs)

Override the select method of the Query object.

The return value of this method is used as the result of query.select() if the value is anything other than EXT_CONTINUE.

DEPRECATED.

def select_by(self, query, *args, **kwargs)

Override the select_by method of the Query object.

The return value of this method is used as the result of query.select_by() if the value is anything other than EXT_CONTINUE.

DEPRECATED.

def translate_row(self, mapper, context, row)

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

This is called as the very first step in the _instance() method.

back to section top

class PropComparator(ColumnOperators)

defines comparison operations for MapperProperty objects

def __init__(self, prop)

Construct a new PropComparator.

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 contains(self, other)

return true if this collection contains other

def expression_element(self)
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.
back to section top

class Query(object)

Encapsulates the object-fetching operations provided by Mappers.

def __init__(self, class_or_mapper, session=None, entity_name=None)

Construct a new Query.

def add_column(self, column, id=None)

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

This will have the effect of all result-returning methods returning a tuple of results, the first element being an instance of the primary class for this Query, and subsequent elements matching columns or entities which were specified via add_column or add_entity.

When adding columns to the result, its generally desireable to add limiting criterion to the query which can associate the primary entity of this Query along with the additional columns, if the column is based on a table or selectable that is not the primary mapped selectable. The Query selects from all tables with no joining criterion by default.

column
a string column name or sql.ColumnElement to be added to the results.
def add_entity(self, entity, alias=None, id=None)

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

This will have the effect of all result-returning methods returning a tuple of results, the first element being an instance of the primary class for this Query, and subsequent elements matching columns or entities which were specified via add_column or add_entity.

When adding entities to the result, its generally desireable to add limiting criterion to the query which can associate the primary entity of this Query along with the additional entities. The Query selects from all tables with no joining criterion by default.

entity
a class or mapper which will be added to the results.
alias
a sqlalchemy.sql.Alias object which will be used to select rows. this will match the usage of the given Alias in filter(), order_by(), etc. expressions
id
a string ID matching that given to query.join() or query.outerjoin(); rows will be selected from the aliased join created via those methods.
def all(self)

Return the results represented by this Query as a list.

This results in an execution of the underlying query.

def apply_avg(self, col)

apply the SQL avg() function against the given column to the query and return the newly resulting Query.

def apply_max(self, col)

apply the SQL max() function against the given column to the query and return the newly resulting Query.

def apply_min(self, col)

apply the SQL min() function against the given column to the query and return the newly resulting Query.

def apply_sum(self, col)

apply the SQL sum() function against the given column to the query and return the newly resulting Query.

def autoflush(self, setting)
def avg(self, col)

Execute the SQL avg() function against the given column.

def compile(self)

compiles and returns a SQL statement based on the criterion and conditions within this Query.

def count(self, whereclause=None, params=None, **kwargs)

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

the whereclause, params and **kwargs arguments are deprecated. use filter() and other generative methods to establish modifiers.

def count_by(*args, **kwargs)

DEPRECATED. use query.filter_by(**params).count()

def distinct(self)

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

def execute(*args, **kwargs)

DEPRECATED. use query.from_statement().all()

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_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, **kwargs)

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 get_by(*args, **kwargs)

DEPRECATED. use query.filter_by(**params).first()

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 quer and return the newly resulting Query.

def instances(self, cursor, *mappers_or_columns, **kwargs)
def iterate_instances(self, cursor, *mappers_or_columns, **kwargs)
def join(self, prop, id=None, aliased=False, from_joinpoint=False)

create a join of this Query object's criterion to a relationship and return the newly resulting Query.

'prop' may be a string property name or a list of string property names.

def join_by(*args, **kwargs)

DEPRECATED. use join() to construct joins based on attribute names.

def join_to(*args, **kwargs)

DEPRECATED. use join() to create joins based on property names.

def join_via(*args, **kwargs)

DEPRECATED. use join() to create joins based on property names.

def limit(self, limit)

Apply a LIMIT to the query and return the newly resulting Query.

def list(*args, **kwargs)

DEPRECATED. use all()

def load(self, ident, raiseerr=True, **kwargs)

Return an instance of the object based on the given identifier.

If not found, raises an exception. The method will remove all pending changes to the object already existing in the Session. 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 max(self, col)

Execute the SQL max() function against the given column.

def min(self, col)

Execute the SQL min() function against the given column.

def offset(self, offset)

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

def one(self)

Return the first result of this Query, raising an exception if more than one row exists.

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, prop, id=None, aliased=False, from_joinpoint=False)

create a left outer join of this Query object's criterion to a relationship and return the newly resulting Query.

'prop' may be a string property name or a list of string property names.

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

This is essentially the en-masse version of load().

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

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 propigated 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(*args, **kwargs)

DEPRECATED. use first()

def select(*args, **kwargs)

DEPRECATED. use query.filter(whereclause).all(), or query.from_statement(statement).all()

def select_by(*args, **kwargs)

DEPRECATED. use use query.filter_by(**params).all().

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 select_statement(*args, **kwargs)

DEPRECATED. Use query.from_statement(statement)

def select_text(*args, **kwargs)

DEPRECATED. Use query.from_statement(statement)

def select_whereclause(*args, **kwargs)

DEPRECATED. use query.filter(whereclause).all()

def selectfirst(*args, **kwargs)

DEPRECATED. use query.filter(whereclause).first()

def selectfirst_by(*args, **kwargs)

DEPRECATED. Use query.filter_by(**kwargs).first()

def selectone(*args, **kwargs)

DEPRECATED. use query.filter(whereclause).one()

def selectone_by(*args, **kwargs)

DEPRECATED. Use query.filter_by(**kwargs).one()

session = property()
def sum(self, col)

Execute the SQL sum() function against the given column.

table = property()
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 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
Up: API Documentation | Previous: module sqlalchemy.types | Next: module sqlalchemy.orm.collections