SQLAlchemy 0.3 Documentation - module sqlalchemy.orm.query

# SQLAlchemy 0.3 Documentation

Multiple Pages | One Page
Version: 0.3.10 Last Updated: 07/20/07 17:20:04

### module sqlalchemy.orm.query

### class Query(object)

Encapsulates the object-fetching operations provided by Mappers.

Note that this particular version of Query contains the 0.3 API as well as most of the 0.4 API for forwards compatibility. A large part of the API here is deprecated (but still present) in the 0.4 series.

def __init__(self, class_or_mapper, session=None, entity_name=None, lockmode=None, with_options=None, extension=None, **kwargs)
def add_column(self, column)

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)

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.

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 avg(self, col)

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

def compile(self, whereclause=None, **kwargs)

Given a WHERE criterion, produce a ClauseElement-based statement suitable for usage in the execute() method.

the arguments to this function are deprecated and are removed in version 0.4.

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

Given a `WHERE` criterion, create a `SELECT COUNT` statement, execute and return the resulting count value.

the additional arguments to this method are is deprecated in 0.4.

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

Return the count of instances based on the given clauses and key/value criterion.

The criterion is constructed in the same way as the `select_by()` method.

this method is deprecated in 0.4.

def distinct(self)

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

def execute(self, clauseelement, params=None, *args, **kwargs)

Execute the given ClauseElement-based statement against this Query's session/mapper, return the resulting list of instances.

this method is deprecated in 0.4. Use from_statement() instead.

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

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

The criterion is constructed in the same way as the `select_by()` method.

def first(self)

Return the first result of this `Query`.

This results in an execution of the underlying query.

this method is for forwards-compatibility with 0.4.

def from_statement(self, statement)

execute a full select() statement, or literal textual string as a SELECT statement.

this method is for forwards compatibility with 0.4.

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(self, *args, **params)

Like `select_by()`, but only return the first as a scalar, or None if no object found. Synonymous with `selectfirst_by()`.

The criterion is constructed in the same way as the `select_by()` method.

this method is deprecated in 0.4.

def group_by(self, criterion)

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

def instances(self, cursor, *mappers_or_columns, **kwargs)

Return a list of mapped instances corresponding to the rows in a given cursor (i.e. `ResultProxy`).

*mappers_or_columns is an optional list containing one or more of classes, mappers, strings or sql.ColumnElements which will be applied to each row and added horizontally to the result set, which becomes a list of tuples. The first element in each tuple is the usual result based on the mapper represented by this `Query`. Each additional element in the tuple corresponds to an entry in the *mappers_or_columns list.

For each element in *mappers_or_columns, if the element is a mapper or mapped class, an additional class instance will be present in the tuple. If the element is a string or sql.ColumnElement, the corresponding result column from each row will be present in the tuple.

Note that when *mappers_or_columns is present, "uniquing" for the result set is disabled, so that the resulting tuples contain entities as they actually correspond. this indicates that multiple results may be present if this option is used.

def join(self, prop)

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 in which it is located in the same manner as keyword arguments in `select_by`, or it may be a list of strings in which case the property is located by direct traversal of each keyname (i.e. like join_via()).

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

Return a `ClauseElement` representing the `WHERE` clause that would normally be sent to `select_whereclause()` by `select_by()`.

The criterion is constructed in the same way as the `select_by()` method.

this method is deprecated in 0.4.

def join_to(self, key)

Given the key name of a property, will recursively descend through all child properties from this Query's mapper to locate the property, and will return a ClauseElement representing a join from this Query's mapper to the endmost mapper.

this method is deprecated in 0.4.

def join_via(self, keys)

Given a list of keys that represents a path from this Query's mapper to a related mapper based on names of relations from one mapper to the next, return a ClauseElement representing a join from this Query's mapper to the endmost mapper.

this method is deprecated in 0.4.

def limit(self, limit)

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

def list(self)

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

This results in an execution of the underlying query.

this method is deprecated in 0.4. use all() instead.

def load(self, ident, **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.

this method is for forwards-compatibility with 0.4.

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

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)

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 in which it is located in the same manner as keyword arguments in `select_by`, or it may be a list of strings in which case the property is located by direct traversal of each keyname (i.e. like join_via()).

def params(self, **kwargs)

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

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.

This is an interim method which will not be needed with new behavior to be released in 0.4.

def scalar(self)

Return the first result of this `Query`.

This results in an execution of the underlying query.

this method will be deprecated in 0.4; first() is added for forwards-compatibility.

def select(self, arg=None, **kwargs)

Select instances of the object from the database.

arg can be any ClauseElement, which will form the criterion with which to load the objects.

For more advanced usage, arg can also be a Select statement object, which will be executed and its resulting rowset used to build new object instances.

In this case, the developer must ensure that an adequate set of columns exists in the rowset with which to build new object instances.

this method is deprecated in 0.4.

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

Return an array of object instances based on the given clauses and key/value criterion.

*args
  a list of zero or more `ClauseElements` which will be connected by `AND` operators.
**params

  > a set of zero or more key/value parameters which are converted into `ClauseElements`. the keys are mapped to property or column names mapped by this mapper's Table, and the values are coerced into a `WHERE` clause separated by `AND` operators. If the local property/column names dont contain the key, a search will be performed against this mapper's immediate list of relations as well, forming the appropriate join conditions if a matching property is located.

  > if the located property is a column-based property, the comparison value should be a scalar with an appropriate type. If the property is a relationship-bound property, the comparison value should be an instance of the related class.

  > E.g.:

  >     result = usermapper.select_by(user_name = 'fred')

  this method is deprecated in 0.4.

def select_from(self, from_obj)

Set the from_obj parameter of the query and return the newly resulting `Query`.

from_obj is a list of one or more tables.

def select_statement(self, statement, **params)

Given a `ClauseElement`-based statement, execute and return the resulting instances.

this method is deprecated in 0.4.

def select_text(self, text, **params)

Given a literal string-based statement, execute and return the resulting instances.

this method is deprecated in 0.4. use from_statement() instead.

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

Given a `WHERE` criterion, create a `SELECT` statement, execute and return the resulting instances.

this method is deprecated in 0.4.

def selectfirst(self, arg=None, **kwargs)

Query for a single instance using the given criterion.

Arguments are the same as `select()`. In the case that the given criterion represents `WHERE` criterion only, LIMIT 1 is applied to the fully generated statement.

this method is deprecated in 0.4.

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

Like `select_by()`, but only return the first as a scalar, or None if no object found. Synonymous with `get_by()`.

The criterion is constructed in the same way as the `select_by()` method.

this method is deprecated in 0.4.

def selectone(self, arg=None, **kwargs)

Query for a single instance using the given criterion.

Unlike `selectfirst`, this method asserts that only one row exists. In the case that the given criterion represents `WHERE` criterion only, LIMIT 2 is applied to the fully generated statement.

this method is deprecated in 0.4.

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

Like `selectfirst_by()`, but throws an error if not exactly one result was returned.

The criterion is constructed in the same way as the `select_by()` method.

this method is deprecated in 0.4.

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.

back to section top

### class QueryContext(OperationContext)

Created within the `Query.compile()` method to store and share state among all the Mappers and MapperProperty objects used in a query construction.

def __init__(self, query, kwargs)
def accept_option(self, opt)

Accept a `MapperOption` which will process (modify) the state of this `QueryContext`.

def select_args(self)

Return a dictionary of attributes from this `QueryContext` that can be applied to a `sql.Select` statement.

back to section top

### class SelectionContext(OperationContext)

Created within the `query.instances()` method to store and share state among all the Mappers and MapperProperty objects used in a load operation.

SelectionContext contains these attributes:

mapper
  The Mapper which originated the instances() call.
session
  The Session that is relevant to the instances call.
identity_map
  A dictionary which stores newly created instances that have not yet been added as persistent to the Session.
attributes
  A dictionary to store arbitrary data; eager loaders use it to store additional result lists.
populate_existing
  Indicates if its OK to overwrite the attributes of instances that were already in the Session.
version_check
  Indicates if mappers that have version_id columns should verify that instances existing already within the Session should have this attribute compared to the freshly loaded value.

def __init__(self, mapper, session, extension, **kwargs)
def accept_option(self, opt)

Accept a MapperOption which will process (modify) the state of this SelectionContext.

back to section top