Query is produced in terms of a given Session, using the query() function:
q = session.query(SomeMappedClass)
Following is the full interface for the Query object.
Encapsulates the object-fetching operations provided by Mappers.
Return the results represented by this Query as a list.
This results in an execution of the underlying query.
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.
Apply this query’s criterion to a SELECT COUNT statement.
If column expressions or LIMIT/OFFSET/DISTINCT are present, the query “SELECT count(1) FROM (SELECT ...)” is issued, so that the result matches the total number of rows this query would return. For mapped entities, the primary key columns of each is written to the columns clause of the nested SELECT statement.
For a Query which is only against mapped entities, a simpler “SELECT count(1) FROM table1, table2, ... WHERE criterion” is issued.
Perform a bulk delete query.
Deletes rows matched by this query from the database.
Parameter: | synchronize_session – chooses the strategy for the removal of matched objects from the session. Valid values are:
|
---|
Returns the number of rows deleted, excluding any cascades.
The method does not offer in-Python cascading of relations - it is assumed that ON DELETE CASCADE is configured for any foreign key references which require it. The Session needs to be expired (occurs automatically after commit(), or call expire_all()) in order for the state of dependent objects subject to delete or delete-orphan cascade to be correctly represented.
Also, the before_delete() and after_delete() MapperExtension methods are not called from this method. For a delete hook here, use the after_bulk_delete() MapperExtension method.
Control whether or not eager joins are rendered.
When set to False, the returned Query will not render eager joins regardless of eagerload() options or mapper-level lazy=False configurations.
This is used primarily when nesting the Query’s statement into a subquery or other selectable.
Produce an EXCEPT of this Query against one or more queries.
Works the same way as union(). See that method for usage examples.
Produce an EXCEPT ALL of this Query against one or more queries.
Works the same way as union(). See that method for usage examples.
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.
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.
return a Query that selects from this Query’s SELECT statement.
*entities - optional list of entities which will replace those being selected.
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.
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.
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
Produce an INTERSECT of this Query against one or more queries.
Works the same way as union(). See that method for usage examples.
Produce an INTERSECT ALL of this Query against one or more queries.
Works the same way as union(). See that method for usage examples.
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
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.
Apply a LIMIT to the query and return the newly resulting
Query.
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.
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.
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.
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().
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.
a persistent or detached instance which is related to class represented by this query.
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.
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.
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.
return the full SELECT statement represented by this Query, embedded within an Alias.
Eager JOIN generation within the query is disabled.
Produce a UNION of this Query against one or more queries.
e.g.:
q1 = sess.query(SomeClass).filter(SomeClass.foo=='bar')
q2 = sess.query(SomeClass).filter(SomeClass.bar=='foo')
q3 = q1.union(q2)
The method accepts multiple Query objects so as to control the level of nesting. A series of union() calls such as:
x.union(y).union(z).all()
will nest on each union(), and produces:
SELECT * FROM (SELECT * FROM (SELECT * FROM X UNION SELECT * FROM y) UNION SELECT * FROM Z)
Whereas:
x.union(y, z).all()
produces:
SELECT * FROM (SELECT * FROM X UNION SELECT * FROM y UNION SELECT * FROM Z)
Produce a UNION ALL of this Query against one or more queries.
Works the same way as union(). See that method for usage examples.
Perform a bulk update query.
Updates rows matched by this query in the database.
Parameters: |
|
---|
Returns the number of rows matched by the update.
The method does not offer in-Python cascading of relations - it is assumed that ON UPDATE CASCADE is configured for any foreign key references which require it. The Session needs to be expired (occurs automatically after commit(), or call expire_all()) in order for the state of dependent objects subject foreign key cascade to be correctly represented.
Also, the before_update() and after_update() MapperExtension methods are not called from this method. For an update hook here, use the after_bulk_update() SessionExtension method.
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.
Add a join criterion corresponding to a relationship to the given parent instance.
Currently, this method only works with immediate parent relationships, but in the future may be enhanced to work across a chain of parent mappers.
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.
Parameters: |
|
---|
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.
Produce an inner join between left and right clauses.
In addition to the interface provided by join(), left and right may be mapped classes or AliasedClass instances. The onclause may be a string name of a relation(), or a class-bound descriptor representing a relation.
join_to_left indicates to attempt aliasing the ON clause, in whatever form it is passed, to the selectable passed as the left side. If False, the onclause is used as is.
Produce a left outer join between left and right clauses.
In addition to the interface provided by outerjoin(), left and right may be mapped classes or AliasedClass instances. The onclause may be a string name of a relation(), or a class-bound descriptor representing a relation.
Options which are passed to query.options(), to affect the behavior of loading.
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.
Return a MapperOption that will convert the column property of the given name into a deferred load.
Used with query.options()
Return a MapperOption that will convert the property of the given name into an eager load.
Used with query.options().
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().
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().
Return a MapperOption that will convert the property of the given name into a lazy load.
Used with query.options().
Return a MapperOption that will convert the column property of the given name into a non-deferred (regular column) load.
Used with query.options().