SQLAlchemy 0.5 Documentation - module sqlalchemy.orm.query

# SQLAlchemy 0.5 Documentation

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

### module sqlalchemy.orm.query

The Query class and support.

Defines the Query class, the central construct used by the ORM to construct database queries.

The `Query` class should not be confused with the Select class, which defines database SELECT operations at the SQL (non-ORM) level. `Query` differs from `Select` in that it returns ORM-mapped objects and interacts with an ORM session, whereas the `Select` construct interacts directly with the database to return iterable result sets.

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