class documentation

class Query(_SelectFromElements, SupportsCloneAnnotations, HasPrefixes, HasSuffixes, HasHints, Executable):

Known subclasses: sqlalchemy.ext.horizontal_shard.ShardedQuery, sqlalchemy.orm.dynamic.AppenderQuery

View In Hierarchy

ORM-level SQL construction object.

_query.Query is the source of all SELECT statements generated by the ORM, both those formulated by end-user query operations as well as by high level internal operations such as related collection loading. It features a generative interface whereby successive calls return a new _query.Query object, a copy of the former with additional criteria and options associated with it.

_query.Query objects are normally initially generated using the ~.Session.query method of .Session, and in less common cases by instantiating the _query.Query directly and associating with a .Session using the _query.Query.with_session method.

For a full walk through of _query.Query usage, see the :ref:`ormtutorial_toplevel`.

Method __clause​_element__ Undocumented
Method __getitem__ Undocumented
Method __init__ Construct a _query.Query directly.
Method __iter__ Undocumented
Method __str__ Undocumented
Method ​_clone Undocumented
Method ​_compile​_context Undocumented
Method ​_compile​_state Create an out-of-compiler ORMCompileState object.
Method ​_entity​_from​_pre​_ent​_zero Undocumented
Method ​_filter​_by​_zero for the filter_by() method, return the target entity for which we will attempt to derive an expression from based on string name.
Method ​_final​_statement Return the 'final' SELECT statement for this .Query.
Method ​_from​_selectable Undocumented
Method ​_from​_self Undocumented
Method ​_get​_bind​_args Undocumented
Method ​_get​_condition Undocumented
Method ​_get​_existing​_condition Undocumented
Method ​_get​_impl Undocumented
Method ​_get​_options Undocumented
Method ​_iter Undocumented
Method ​_next​_aliased​_generation Undocumented
Method ​_no​_clauseelement​_condition Undocumented
Method ​_no​_criterion​_assertion Undocumented
Method ​_no​_criterion​_condition Undocumented
Method ​_no​_limit​_offset Undocumented
Method ​_no​_statement​_condition Undocumented
Method ​_only​_full​_mapper​_zero Undocumented
Method ​_set​_enable​_single​_crit Undocumented
Method ​_set​_entities Undocumented
Method ​_set​_lazyload​_from Undocumented
Method ​_set​_op Undocumented
Method ​_set​_propagate​_attrs Undocumented
Method ​_set​_select​_from Undocumented
Method ​_statement​_20 Undocumented
Method ​_with​_compile​_options Undocumented
Method ​_with​_current​_path indicate that this query applies to objects loaded within a certain path.
Method ​_with​_invoke​_all​_eagers Set the 'invoke all eagers' flag which causes joined- and subquery loaders to traverse into already-loaded related objects and collections.
Method add​_column Add a column expression to the list of result columns to be returned.
Method add​_columns Add one or more column expressions to the list of result columns to be returned.
Method add​_entity add a mapped entity to the list of result columns to be returned.
Method all Return the results represented by this _query.Query as a list.
Method as​_scalar Return the full SELECT statement represented by this _query.Query, converted to a scalar subquery.
Method autoflush Return a Query with a specific 'autoflush' setting.
Method correlate Return a .Query construct which will correlate the given FROM clauses to that of an enclosing .Query or ~.expression.select.
Method count Return a count of rows this the SQL formed by this Query would return.
Method cte Return the full SELECT statement represented by this _query.Query represented as a common table expression (CTE).
Method delete Perform a DELETE with an arbitrary WHERE clause.
Method distinct Apply a DISTINCT to the query and return the newly resulting Query.
Method enable​_assertions Control whether assertions are generated.
Method enable​_eagerloads Control whether or not eager joins and subqueries are rendered.
Method except​_ Produce an EXCEPT of this Query against one or more queries.
Method except​_all Produce an EXCEPT ALL of this Query against one or more queries.
Method execution​_options Set non-SQL options which take effect during execution.
Method exists A convenience method that turns a query into an EXISTS subquery of the form EXISTS (SELECT 1 FROM ... WHERE ...).
Method filter Apply the given filtering criterion to a copy of this _query.Query, using SQL expressions.
Method filter​_by Apply the given filtering criterion to a copy of this _query.Query, using keyword expressions.
Method first Return the first result of this Query or None if the result doesn't contain any row.
Method from​_self return a Query that selects from this Query's SELECT statement.
Method from​_statement Execute the given SELECT statement and return results.
Method get Return an instance based on the given primary key identifier, or None if not found.
Method get​_execution​_options Get the non-SQL options which will take effect during execution.
Method group​_by Apply one or more GROUP BY criterion to the query and return the newly resulting _query.Query.
Method having Apply a HAVING criterion to the query and return the newly resulting _query.Query.
Method instances Return an ORM result given a _engine.CursorResult and .QueryContext.
Method intersect Produce an INTERSECT of this Query against one or more queries.
Method intersect​_all Produce an INTERSECT ALL of this Query against one or more queries.
Method join No summary
Method label Return the full SELECT statement represented by this _query.Query, converted to a scalar subquery with a label of the given name.
Method limit Apply a LIMIT to the query and return the newly resulting Query.
Method merge​_result Merge a result into this _query.Query object's Session.
Method offset Apply an OFFSET to the query and return the newly resulting Query.
Method one Return exactly one result or raise an exception.
Method one​_or​_none Return at most one result or raise an exception.
Method only​_return​_tuples When set to True, the query results will always be a tuple.
Method options Return a new _query.Query object, applying the given list of mapper options.
Method order​_by Apply one or more ORDER BY criteria to the query and return the newly resulting _query.Query.
Method outerjoin Create a left outer join against this Query object's criterion and apply generatively, returning the newly resulting Query.
Method params Add values for bind parameters which may have been specified in filter().
Method populate​_existing Return a _query.Query that will expire and refresh all instances as they are loaded, or reused from the current .Session.
Method reset​_joinpoint Return a new .Query, where the "join point" has been reset back to the base FROM entities of the query.
Method scalar Return the first element of the first result or None if no rows present. If multiple rows are returned, raises MultipleResultsFound.
Method scalar​_subquery Return the full SELECT statement represented by this _query.Query, converted to a scalar subquery.
Method select​_entity​_from Set the FROM clause of this _query.Query to a core selectable, applying it as a replacement FROM clause for corresponding mapped entities.
Method select​_from Set the FROM clause of this .Query explicitly.
Method set​_label​_style Apply column labels to the return value of Query.statement.
Method slice Computes the "slice" of the _query.Query represented by the given indices and returns the resulting _query.Query.
Method subquery Return the full SELECT statement represented by this _query.Query, embedded within an _expression.Alias.
Method union Produce a UNION of this Query against one or more queries.
Method union​_all Produce a UNION ALL of this Query against one or more queries.
Method update Perform an UPDATE with an arbitrary WHERE clause.
Method value Return a scalar result corresponding to the given column expression.
Method values Return an iterator yielding result tuples corresponding to the given list of columns
Method where A synonym for .Query.filter.
Method with​_entities Return a new _query.Query replacing the SELECT list with the given entities.
Method with​_for​_update return a new _query.Query with the specified options for the FOR UPDATE clause.
Method with​_labels Undocumented
Method with​_parent No summary
Method with​_polymorphic Load columns for inheriting classes.
Method with​_session Return a _query.Query that will use the given .Session.
Method with​_transformation Return a new _query.Query object transformed by the given function.
Method yield​_per Yield only count rows at a time.
Class Variable ​_having​_criteria Undocumented
Class Variable ​_memoized​_select​_entities Undocumented
Class Variable ​_setup​_joins Undocumented
Class Variable load​_options Undocumented
Instance Variable ​_aliased​_generation Undocumented
Instance Variable ​_aliased​_generation​_counter Undocumented
Instance Variable ​_auto​_correlate Undocumented
Instance Variable ​_compile​_options Undocumented
Instance Variable ​_correlate Undocumented
Instance Variable ​_distinct Undocumented
Instance Variable ​_distinct​_on Undocumented
Instance Variable ​_enable​_assertions Undocumented
Instance Variable ​_execution​_options Undocumented
Instance Variable ​_for​_update​_arg Undocumented
Instance Variable ​_from​_obj Undocumented
Instance Variable ​_group​_by​_clauses Undocumented
Instance Variable ​_label​_style Undocumented
Instance Variable ​_last​_joined​_entity Undocumented
Instance Variable ​_legacy​_setup​_joins Undocumented
Instance Variable ​_limit​_clause Undocumented
Instance Variable ​_offset​_clause Undocumented
Instance Variable ​_order​_by​_clauses Undocumented
Instance Variable ​_params Undocumented
Instance Variable ​_propagate​_attrs Undocumented
Instance Variable ​_raw​_columns Undocumented
Instance Variable ​_statement Undocumented
Instance Variable ​_where​_criteria Undocumented
Instance Variable session Undocumented
Property ​_current​_path Undocumented
Property ​_has​_row​_limiting​_clause Undocumented
Property column​_descriptions Return metadata about the columns which would be returned by this _query.Query.
Property get​_label​_style Retrieve the current label style.
Property is​_single​_entity Indicates if this _query.Query returns tuples or single entities.
Property lazy​_loaded​_from An .InstanceState that is using this _query.Query for a lazy load operation.
Property selectable Return the _expression.Select object emitted by this _query.Query.
Property statement The full SELECT statement represented by this Query.
Property whereclause A readonly attribute which returns the current WHERE criterion for this Query.

Inherited from _SelectFromElements:

Method ​_iterate​_from​_elements Undocumented

Inherited from SupportsCloneAnnotations:

Method ​_annotate return a copy of this ClauseElement with annotations updated by the given dictionary.
Method ​_deannotate return a copy of this _expression.ClauseElement with annotations removed.
Method ​_with​_annotations return a copy of this ClauseElement with annotations replaced by the given dictionary.
Class Variable ​_clone​_annotations​_traverse​_internals Undocumented

Inherited from SupportsAnnotations (via SupportsCloneAnnotations):

Property ​_annotations​_cache​_key Undocumented

Inherited from HasPrefixes:

Method ​_setup​_prefixes Undocumented
Method prefix​_with Add one or more expressions following the statement keyword, i.e. SELECT, INSERT, UPDATE, or DELETE. Generative.
Class Variable ​_has​_prefixes​_traverse​_internals Undocumented
Instance Variable ​_prefixes Undocumented

Inherited from HasSuffixes:

Method ​_setup​_suffixes Undocumented
Method suffix​_with Add one or more expressions following the statement as a whole.
Class Variable ​_has​_suffixes​_traverse​_internals Undocumented
Instance Variable ​_suffixes Undocumented

Inherited from HasHints:

Method with​_hint Add an indexing or other executional context hint for the given selectable to this _expression.Select or other selectable object.
Method with​_statement​_hint Add a statement hint to this _expression.Select or other selectable object.
Class Variable ​_has​_hints​_traverse​_internals Undocumented
Class Variable ​_hints Undocumented
Class Variable ​_statement​_hints Undocumented

Inherited from Executable:

Method ​_add​_context​_option Add a context option to this statement.
Method ​_set​_compile​_options Assign the compile options to a new value.
Method ​_update​_compile​_options update the _compile_options with new keys.
Method execute Compile and execute this .Executable.
Class Variable ​_bind Undocumented
Class Variable ​_executable​_traverse​_internals Undocumented
Class Variable ​_with​_context​_options Undocumented
Class Variable ​_with​_options Undocumented
Class Variable is​_delete Undocumented
Class Variable is​_dml Undocumented
Class Variable is​_insert Undocumented
Class Variable is​_select Undocumented
Class Variable is​_text Undocumented
Class Variable is​_update Undocumented
Class Variable supports​_execution Undocumented
Property ​_effective​_plugin​_target Undocumented
Property bind Returns the _engine.Engine or _engine.Connection to which this .Executable is bound, or None if none found.

Inherited from StatementRole (via Executable):

Class Variable ​_role​_name Undocumented

Inherited from SQLRole (via Executable, StatementRole):

Class Variable allows​_lambda Undocumented
Class Variable uses​_inspection Undocumented

Inherited from Generative (via Executable):

Method ​_generate Undocumented
def __clause_element__(self):

Undocumented

def __getitem__(self, item):

Undocumented

def __init__(self, entities, session=None):

Construct a _query.Query directly.

E.g.:

q = Query([User, Address], session=some_session)

The above is equivalent to:

q = some_session.query(User, Address)

See Also

.Session.query

_query.Query.with_session

Parameters
entitiesa sequence of entities and/or SQL expressions.
sessiona .Session with which the _query.Query will be associated. Optional; a _query.Query can be associated with a .Session generatively via the _query.Query.with_session method as well.
def __iter__(self):

Undocumented

def __str__(self):

Undocumented

def _clone(self):

Undocumented

def _compile_context(self, for_statement=False):

Undocumented

def _compile_state(self, for_statement=False, **kw):

Create an out-of-compiler ORMCompileState object.

The ORMCompileState object is normally created directly as a result of the SQLCompiler.process() method being handed a Select() or FromStatement() object that uses the "orm" plugin. This method provides a means of creating this ORMCompileState object directly without using the compiler.

This method is used only for deprecated cases, which include the .from_self() method for a Query that has multiple levels of .from_self() in use, as well as the instances() method. It is also used within the test suite to generate ORMCompileState objects for test purposes.

def _entity_from_pre_ent_zero(self):

Undocumented

def _filter_by_zero(self):
for the filter_by() method, return the target entity for which we will attempt to derive an expression from based on string name.
def _final_statement(self, legacy_query_style=True):

Return the 'final' SELECT statement for this .Query.

This is the Core-only select() that will be rendered by a complete compilation of this query, and is what .statement used to return in 1.3.

This method creates a complete compile state so is fairly expensive.

@_generative
def _from_selectable(self, fromclause, set_entity_from=True):

Undocumented

def _from_self(self, *entities):

Undocumented

def _get_bind_args(self, statement, fn, **kw):

Undocumented

def _get_condition(self):

Undocumented

def _get_existing_condition(self):

Undocumented

def _get_impl(self, primary_key_identity, db_load_fn, identity_token=None):

Undocumented

def _get_options(self, populate_existing=None, version_check=None, only_load_props=None, refresh_state=None, identity_token=None):

Undocumented

def _iter(self):

Undocumented

def _next_aliased_generation(self):

Undocumented

def _no_clauseelement_condition(self, meth):

Undocumented

def _no_criterion_assertion(self, meth, order_by=True, distinct=True):

Undocumented

def _no_criterion_condition(self, meth, order_by=True, distinct=True):

Undocumented

def _no_limit_offset(self, meth):

Undocumented

def _no_statement_condition(self, meth):

Undocumented

def _only_full_mapper_zero(self, methname):

Undocumented

@_generative
def _set_enable_single_crit(self, val):

Undocumented

def _set_entities(self, entities):

Undocumented

@_generative
def _set_lazyload_from(self, state):

Undocumented

def _set_op(self, expr_fn, *q):

Undocumented

def _set_propagate_attrs(self, values):

Undocumented

def _set_select_from(self, obj, set_base_alias):

Undocumented

def _statement_20(self, for_statement=False, use_legacy_query_style=True):

Undocumented

@_generative
def _with_compile_options(self, **opt):

Undocumented

@_generative
def _with_current_path(self, path):

indicate that this query applies to objects loaded within a certain path.

Used by deferred loaders (see strategies.py) which transfer query options from an originating query to a newly generated query intended for the deferred load.

@_generative
def _with_invoke_all_eagers(self, value):

Set the 'invoke all eagers' flag which causes joined- and subquery loaders to traverse into already-loaded related objects and collections.

Default is that of _query.Query._invoke_all_eagers.

@util.deprecated('1.4', ':meth:`_query.Query.add_column` is deprecated and will be removed in a future release. Please use :meth:`_query.Query.add_columns`')
def add_column(self, column):
Add a column expression to the list of result columns to be returned.
@_generative
def add_columns(self, *column):
Add one or more column expressions to the list of result columns to be returned.
@_generative
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.Query as a list.

This results in an execution of the underlying SQL statement.

Warning

The _query.Query object, when asked to return either a sequence or iterator that consists of full ORM-mapped entities, will deduplicate entries based on primary key. See the FAQ for more details.

@util.deprecated('1.4', 'The :meth:`_query.Query.as_scalar` method is deprecated and will be removed in a future release. Please refer to :meth:`_query.Query.scalar_subquery`.')
def as_scalar(self):
Return the full SELECT statement represented by this _query.Query, converted to a scalar subquery.
@_generative
def autoflush(self, setting):

Return a Query with a specific 'autoflush' setting.

As of SQLAlchemy 1.4, the _orm.Query.autoflush method is equivalent to using the autoflush execution option at the ORM level. See the section :ref:`orm_queryguide_autoflush` for further background on this option.

@_generative
def correlate(self, *fromclauses):

Return a .Query construct which will correlate the given FROM clauses to that of an enclosing .Query or ~.expression.select.

The method here accepts mapped classes, .aliased constructs, and .mapper constructs as arguments, which are resolved into expression constructs, in addition to appropriate expression constructs.

The correlation arguments are ultimately passed to _expression.Select.correlate after coercion to expression constructs.

The correlation arguments take effect in such cases as when _query.Query.from_self is used, or when a subquery as returned by _query.Query.subquery is embedded in another _expression.select construct.

def count(self):

Return a count of rows this the SQL formed by this Query would return.

This generates the SQL for this Query as follows:

SELECT count(1) AS count_1 FROM (
    SELECT <rest of query follows...>
) AS anon_1

The above SQL returns a single row, which is the aggregate value of the count function; the _query.Query.count method then returns that single integer value.

Warning

It is important to note that the value returned by count() is not the same as the number of ORM objects that this Query would return from a method such as the .all() method. The _query.Query object, when asked to return full entities, will deduplicate entries based on primary key, meaning if the same primary key value would appear in the results more than once, only one object of that primary key would be present. This does not apply to a query that is against individual columns.

For fine grained control over specific columns to count, to skip the usage of a subquery or otherwise control of the FROM clause, or to use other aggregate functions, use ~sqlalchemy.sql.expression.func expressions in conjunction with ~.Session.query, i.e.:

from sqlalchemy import func

# count User records, without
# using a subquery.
session.query(func.count(User.id))

# return count of user "id" grouped
# by "name"
session.query(func.count(User.id)).\
        group_by(User.name)

from sqlalchemy import distinct

# count distinct "name" values
session.query(func.count(distinct(User.name)))
def cte(self, name=None, recursive=False, nesting=False):

Return the full SELECT statement represented by this _query.Query represented as a common table expression (CTE).

Parameters and usage are the same as those of the _expression.SelectBase.cte method; see that method for further details.

Here is the PostgreSQL WITH RECURSIVE example. Note that, in this example, the included_parts cte and the incl_alias alias of it are Core selectables, which means the columns are accessed via the .c. attribute. The parts_alias object is an _orm.aliased instance of the Part entity, so column-mapped attributes are available directly:

from sqlalchemy.orm import aliased

class Part(Base):
    __tablename__ = 'part'
    part = Column(String, primary_key=True)
    sub_part = Column(String, primary_key=True)
    quantity = Column(Integer)

included_parts = session.query(
                Part.sub_part,
                Part.part,
                Part.quantity).\
                    filter(Part.part=="our part").\
                    cte(name="included_parts", recursive=True)

incl_alias = aliased(included_parts, name="pr")
parts_alias = aliased(Part, name="p")
included_parts = included_parts.union_all(
    session.query(
        parts_alias.sub_part,
        parts_alias.part,
        parts_alias.quantity).\
            filter(parts_alias.part==incl_alias.c.sub_part)
    )

q = session.query(
        included_parts.c.sub_part,
        func.sum(included_parts.c.quantity).
            label('total_quantity')
    ).\
    group_by(included_parts.c.sub_part)

See Also

_expression.HasCTE.cte

def delete(self, synchronize_session='evaluate'):

Perform a DELETE with an arbitrary WHERE clause.

Deletes rows matched by this query from the database.

E.g.:

sess.query(User).filter(User.age == 25).\
    delete(synchronize_session=False)

sess.query(User).filter(User.age == 25).\
    delete(synchronize_session='evaluate')

Warning

See the section :ref:`orm_expression_update_delete` for important caveats and warnings, including limitations when using bulk UPDATE and DELETE with mapper inheritance configurations.

Parameters
synchronize​_sessionchooses the strategy to update the attributes on objects in the session. See the section :ref:`orm_expression_update_delete` for a discussion of these strategies.
Returns
the count of rows matched as returned by the database's "row count" feature.
@_generative
@_assertions(_no_statement_condition)
def distinct(self, *expr):

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

Note

The ORM-level .distinct call includes logic that will automatically add columns from the ORDER BY of the query to the columns clause of the SELECT statement, to satisfy the common need of the database backend that ORDER BY columns be part of the SELECT list when DISTINCT is used. These columns are not added to the list of columns actually fetched by the _query.Query, however, so would not affect results. The columns are passed through when using the _query.Query.statement accessor, however.

Deprecated since version 2.0: This logic is deprecated and will be removed in SQLAlchemy 2.0. See :ref:`migration_20_query_distinct` for a description of this use case in 2.0.
Parameters
*expr

optional column expressions. When present, the PostgreSQL dialect will render a DISTINCT ON (<expressions>) construct.

Deprecated since version 1.4: Using *expr in other dialects is deprecated and will raise _exc.CompileError in a future version.
@_generative
def enable_assertions(self, value):

Control whether assertions are generated.

When set to False, the returned Query will not assert its state before certain operations, including that LIMIT/OFFSET has not been applied when filter() is called, no criterion exists when get() is called, and no "from_statement()" exists when filter()/order_by()/group_by() etc. is called. This more permissive mode is used by custom Query subclasses to specify criterion or other modifiers outside of the usual usage patterns.

Care should be taken to ensure that the usage pattern is even possible. A statement applied by from_statement() will override any criterion set by filter() or order_by(), for example.

@_generative
def enable_eagerloads(self, value):

Control whether or not eager joins and subqueries are rendered.

When set to False, the returned Query will not render eager joins regardless of ~sqlalchemy.orm.joinedload, ~sqlalchemy.orm.subqueryload options or mapper-level lazy='joined'/lazy='subquery' configurations.

This is used primarily when nesting the Query's statement into a subquery or other selectable, or when using _query.Query.yield_per.

def except_(self, *q):

Produce an EXCEPT of this Query against one or more queries.

Works the same way as ~sqlalchemy.orm.query.Query.union. See that method for usage examples.

def except_all(self, *q):

Produce an EXCEPT ALL of this Query against one or more queries.

Works the same way as ~sqlalchemy.orm.query.Query.union. See that method for usage examples.

@_generative
def execution_options(self, **kwargs):

Set non-SQL options which take effect during execution.

Options allowed here include all of those accepted by _engine.Connection.execution_options, as well as a series of ORM specific options:

populate_existing=True - equivalent to using _orm.Query.populate_existing

autoflush=True|False - equivalent to using _orm.Query.autoflush

yield_per=<value> - equivalent to using _orm.Query.yield_per

Note that the stream_results execution option is enabled automatically if the ~sqlalchemy.orm.query.Query.yield_per() method or execution option is used.

The execution options may also be specified on a per execution basis when using :term:`2.0 style` queries via the :paramref:`_orm.Session.execution_options` parameter.

New in version 1.4: - added ORM options to _orm.Query.execution_options

See Also

:ref:`engine_stream_results`

_query.Query.get_execution_options

def exists(self):

A convenience method that turns a query into an EXISTS subquery of the form EXISTS (SELECT 1 FROM ... WHERE ...).

e.g.:

q = session.query(User).filter(User.name == 'fred')
session.query(q.exists())

Producing SQL similar to:

SELECT EXISTS (
    SELECT 1 FROM users WHERE users.name = :name_1
) AS anon_1

The EXISTS construct is usually used in the WHERE clause:

session.query(User.id).filter(q.exists()).scalar()

Note that some databases such as SQL Server don't allow an EXISTS expression to be present in the columns clause of a SELECT. To select a simple boolean value based on the exists as a WHERE, use .literal:

from sqlalchemy import literal

session.query(literal(True)).filter(q.exists()).scalar()

Apply the given filtering criterion to a copy of this _query.Query, using SQL expressions.

e.g.:

session.query(MyClass).filter(MyClass.name == 'some name')

Multiple criteria may be specified as comma separated; the effect is that they will be joined together using the .and_ function:

session.query(MyClass).\
    filter(MyClass.name == 'some name', MyClass.id > 5)

The criterion is any SQL expression object applicable to the WHERE clause of a select. String expressions are coerced into SQL expression constructs via the _expression.text construct.

See Also

_query.Query.filter_by - filter on keyword expressions.

def filter_by(self, **kwargs):

Apply the given filtering criterion to a copy of this _query.Query, using keyword expressions.

e.g.:

session.query(MyClass).filter_by(name = 'some name')

Multiple criteria may be specified as comma separated; the effect is that they will be joined together using the .and_ function:

session.query(MyClass).\
    filter_by(name = 'some name', id = 5)

The keyword expressions are extracted from the primary entity of the query, or the last entity that was the target of a call to _query.Query.join.

See Also

_query.Query.filter - filter on SQL expressions.

def first(self):

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

first() applies a limit of one within the generated SQL, so that only one primary entity row is generated on the server side (note this may consist of multiple result rows if join-loaded collections are present).

Calling _query.Query.first results in an execution of the underlying query.

See Also

_query.Query.one

_query.Query.one_or_none

@util.deprecated_20(':meth:`_query.Query.from_self`', alternative='The new approach is to use the :func:`.orm.aliased` construct in conjunction with a subquery. See the section :ref:`Selecting from the query itself as a subquery <migration_20_query_from_self>` in the 2.0 migration notes for an example.')
def from_self(self, *entities):

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

_query.Query.from_self essentially turns the SELECT statement into a SELECT of itself. Given a query such as:

q = session.query(User).filter(User.name.like('e%'))

Given the _query.Query.from_self version:

q = session.query(User).filter(User.name.like('e%')).from_self()

This query renders as:

SELECT anon_1.user_id AS anon_1_user_id,
       anon_1.user_name AS anon_1_user_name
FROM (SELECT "user".id AS user_id, "user".name AS user_name
FROM "user"
WHERE "user".name LIKE :name_1) AS anon_1

There are lots of cases where _query.Query.from_self may be useful. A simple one is where above, we may want to apply a row LIMIT to the set of user objects we query against, and then apply additional joins against that row-limited set:

q = session.query(User).filter(User.name.like('e%')).\
    limit(5).from_self().\
    join(User.addresses).filter(Address.email.like('q%'))

The above query joins to the Address entity but only against the first five results of the User query:

SELECT anon_1.user_id AS anon_1_user_id,
       anon_1.user_name AS anon_1_user_name
FROM (SELECT "user".id AS user_id, "user".name AS user_name
FROM "user"
WHERE "user".name LIKE :name_1
 LIMIT :param_1) AS anon_1
JOIN address ON anon_1.user_id = address.user_id
WHERE address.email LIKE :email_1

Automatic Aliasing

Another key behavior of _query.Query.from_self is that it applies automatic aliasing to the entities inside the subquery, when they are referenced on the outside. Above, if we continue to refer to the User entity without any additional aliasing applied to it, those references will be in terms of the subquery:

q = session.query(User).filter(User.name.like('e%')).\
    limit(5).from_self().\
    join(User.addresses).filter(Address.email.like('q%')).\
    order_by(User.name)

The ORDER BY against User.name is aliased to be in terms of the inner subquery:

SELECT anon_1.user_id AS anon_1_user_id,
       anon_1.user_name AS anon_1_user_name
FROM (SELECT "user".id AS user_id, "user".name AS user_name
FROM "user"
WHERE "user".name LIKE :name_1
 LIMIT :param_1) AS anon_1
JOIN address ON anon_1.user_id = address.user_id
WHERE address.email LIKE :email_1 ORDER BY anon_1.user_name

The automatic aliasing feature only works in a limited way, for simple filters and orderings. More ambitious constructions such as referring to the entity in joins should prefer to use explicit subquery objects, typically making use of the _query.Query.subquery method to produce an explicit subquery object. Always test the structure of queries by viewing the SQL to ensure a particular structure does what's expected!

Changing the Entities

_query.Query.from_self also includes the ability to modify what columns are being queried. In our example, we want User.id to be queried by the inner query, so that we can join to the Address entity on the outside, but we only wanted the outer query to return the Address.email column:

q = session.query(User).filter(User.name.like('e%')).\
    limit(5).from_self(Address.email).\
    join(User.addresses).filter(Address.email.like('q%'))

yielding:

SELECT address.email AS address_email
FROM (SELECT "user".id AS user_id, "user".name AS user_name
FROM "user"
WHERE "user".name LIKE :name_1
 LIMIT :param_1) AS anon_1
JOIN address ON anon_1.user_id = address.user_id
WHERE address.email LIKE :email_1

Looking out for Inner / Outer Columns

Keep in mind that when referring to columns that originate from inside the subquery, we need to ensure they are present in the columns clause of the subquery itself; this is an ordinary aspect of SQL. For example, if we wanted to load from a joined entity inside the subquery using .contains_eager, we need to add those columns. Below illustrates a join of Address to User, then a subquery, and then we'd like .contains_eager to access the User columns:

q = session.query(Address).join(Address.user).\
    filter(User.name.like('e%'))

q = q.add_entity(User).from_self().\
    options(contains_eager(Address.user))

We use _query.Query.add_entity above before we call _query.Query.from_self so that the User columns are present in the inner subquery, so that they are available to the .contains_eager modifier we are using on the outside, producing:

SELECT anon_1.address_id AS anon_1_address_id,
       anon_1.address_email AS anon_1_address_email,
       anon_1.address_user_id AS anon_1_address_user_id,
       anon_1.user_id AS anon_1_user_id,
       anon_1.user_name AS anon_1_user_name
FROM (
    SELECT address.id AS address_id,
    address.email AS address_email,
    address.user_id AS address_user_id,
    "user".id AS user_id,
    "user".name AS user_name
FROM address JOIN "user" ON "user".id = address.user_id
WHERE "user".name LIKE :name_1) AS anon_1

If we didn't call add_entity(User), but still asked .contains_eager to load the User entity, it would be forced to add the table on the outside without the correct join criteria - note the anon1, "user" phrase at the end:

-- incorrect query
SELECT anon_1.address_id AS anon_1_address_id,
       anon_1.address_email AS anon_1_address_email,
       anon_1.address_user_id AS anon_1_address_user_id,
       "user".id AS user_id,
       "user".name AS user_name
FROM (
    SELECT address.id AS address_id,
    address.email AS address_email,
    address.user_id AS address_user_id
FROM address JOIN "user" ON "user".id = address.user_id
WHERE "user".name LIKE :name_1) AS anon_1, "user"
Parameters
*entitiesoptional list of entities which will replace those being selected.
@_generative
@_assertions(_no_clauseelement_condition)
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 is typically either a _expression.text or _expression.select construct, and should return the set of columns appropriate to the entity class represented by this _query.Query.

See Also

:ref:`orm_tutorial_literal_sql` - usage examples in the ORM tutorial

@util.deprecated_20(':meth:`_orm.Query.get`', alternative='The method is now available as :meth:`_orm.Session.get`', becomes_legacy=True)
def get(self, ident):

Return an instance based on the given primary key identifier, or None if not found.

E.g.:

my_user = session.query(User).get(5)

some_object = session.query(VersionedFoo).get((5, 10))

some_object = session.query(VersionedFoo).get(
    {"id": 5, "version_id": 10})

_query.Query.get is special in that it provides direct access to the identity map of the owning .Session. If the given primary key identifier is present in the local identity map, the object is returned directly from this collection and no SQL is emitted, unless the object has been marked fully expired. If not present, a SELECT is performed in order to locate the object.

_query.Query.get also will perform a check if the object is present in the identity map and marked as expired - a SELECT is emitted to refresh the object as well as to ensure that the row is still present. If not, ~sqlalchemy.orm.exc.ObjectDeletedError is raised.

_query.Query.get is only used to return a single mapped instance, not multiple instances or individual column constructs, and strictly on a single primary key value. The originating _query.Query must be constructed in this way, i.e. against a single mapped entity, with no additional filtering criterion. Loading options via _query.Query.options may be applied however, and will be used if the object is not yet locally present.

Parameters
ident

A scalar, tuple, or dictionary representing the primary key. For a composite (e.g. multiple column) primary key, a tuple or dictionary should be passed.

For a single-column primary key, the scalar calling form is typically the most expedient. If the primary key of a row is the value "5", the call looks like:

my_object = query.get(5)

The tuple form contains primary key values typically in the order in which they correspond to the mapped _schema.Table object's primary key columns, or if the :paramref:`_orm.Mapper.primary_key` configuration parameter were used, in the order used for that parameter. For example, if the primary key of a row is represented by the integer digits "5, 10" the call would look like:

my_object = query.get((5, 10))

The dictionary form should include as keys the mapped attribute names corresponding to each element of the primary key. If the mapped class has the attributes id, version_id as the attributes which store the object's primary key value, the call would look like:

my_object = query.get({"id": 5, "version_id": 10})
New in version 1.3: the _query.Query.get method now optionally accepts a dictionary of attribute names to values in order to indicate a primary key identifier.
Returns
The object instance, or None.
def get_execution_options(self):

Get the non-SQL options which will take effect during execution.

New in version 1.3.

See Also

_query.Query.execution_options

Apply one or more GROUP BY criterion to the query and return the newly resulting _query.Query.

All existing GROUP BY settings can be suppressed by passing None - this will suppress any GROUP BY configured on mappers as well.

See Also

These sections describe GROUP BY in terms of :term:`2.0 style` invocation but apply to _orm.Query as well:

:ref:`tutorial_group_by_w_aggregates` - in the :ref:`unified_tutorial`

:ref:`tutorial_order_by_label` - in the :ref:`unified_tutorial`

Apply a HAVING criterion to the query and return the newly resulting _query.Query.

_query.Query.having is used in conjunction with _query.Query.group_by.

HAVING criterion makes it possible to use filters on aggregate functions like COUNT, SUM, AVG, MAX, and MIN, eg.:

q = session.query(User.id).\
            join(User.addresses).\
            group_by(User.id).\
            having(func.count(Address.id) > 2)
def instances(self, result_proxy, context=None):
Return an ORM result given a _engine.CursorResult and .QueryContext.
def intersect(self, *q):

Produce an INTERSECT of this Query against one or more queries.

Works the same way as ~sqlalchemy.orm.query.Query.union. See that method for usage examples.

def intersect_all(self, *q):

Produce an INTERSECT ALL of this Query against one or more queries.

Works the same way as ~sqlalchemy.orm.query.Query.union. See that method for usage examples.

@_generative
@_assertions(_no_statement_condition, _no_limit_offset)
def join(self, target, *props, **kwargs):

Create a SQL JOIN against this _query.Query object's criterion and apply generatively, returning the newly resulting _query.Query.

Simple Relationship Joins

Consider a mapping between two classes User and Address, with a relationship User.addresses representing a collection of Address objects associated with each User. The most common usage of _query.Query.join is to create a JOIN along this relationship, using the User.addresses attribute as an indicator for how this should occur:

q = session.query(User).join(User.addresses)

Where above, the call to _query.Query.join along User.addresses will result in SQL approximately equivalent to:

SELECT user.id, user.name
FROM user JOIN address ON user.id = address.user_id

In the above example we refer to User.addresses as passed to _query.Query.join as the "on clause", that is, it indicates how the "ON" portion of the JOIN should be constructed.

To construct a chain of joins, multiple _query.Query.join calls may be used. The relationship-bound attribute implies both the left and right side of the join at once:

q = session.query(User).\
        join(User.orders).\
        join(Order.items).\
        join(Item.keywords)

Note

as seen in the above example, the order in which each call to the join() method occurs is important. Query would not, for example, know how to join correctly if we were to specify User, then Item, then Order, in our chain of joins; in such a case, depending on the arguments passed, it may raise an error that it doesn't know how to join, or it may produce invalid SQL in which case the database will raise an error. In correct practice, the _query.Query.join method is invoked in such a way that lines up with how we would want the JOIN clauses in SQL to be rendered, and each call should represent a clear link from what precedes it.

Joins to a Target Entity or Selectable

A second form of _query.Query.join allows any mapped entity or core selectable construct as a target. In this usage, _query.Query.join will attempt to create a JOIN along the natural foreign key relationship between two entities:

q = session.query(User).join(Address)

In the above calling form, _query.Query.join is called upon to create the "on clause" automatically for us. This calling form will ultimately raise an error if either there are no foreign keys between the two entities, or if there are multiple foreign key linkages between the target entity and the entity or entities already present on the left side such that creating a join requires more information. Note that when indicating a join to a target without any ON clause, ORM configured relationships are not taken into account.

Joins to a Target with an ON Clause

The third calling form allows both the target entity as well as the ON clause to be passed explicitly. A example that includes a SQL expression as the ON clause is as follows:

q = session.query(User).join(Address, User.id==Address.user_id)

The above form may also use a relationship-bound attribute as the ON clause as well:

q = session.query(User).join(Address, User.addresses)

The above syntax can be useful for the case where we wish to join to an alias of a particular target entity. If we wanted to join to Address twice, it could be achieved using two aliases set up using the ~sqlalchemy.orm.aliased function:

a1 = aliased(Address)
a2 = aliased(Address)

q = session.query(User).\
        join(a1, User.addresses).\
        join(a2, User.addresses).\
        filter(a1.email_address=='ed@foo.com').\
        filter(a2.email_address=='ed@bar.com')

The relationship-bound calling form can also specify a target entity using the _orm.PropComparator.of_type method; a query equivalent to the one above would be:

a1 = aliased(Address)
a2 = aliased(Address)

q = session.query(User).\
        join(User.addresses.of_type(a1)).\
        join(User.addresses.of_type(a2)).\
        filter(a1.email_address == 'ed@foo.com').\
        filter(a2.email_address == 'ed@bar.com')

Augmenting Built-in ON Clauses

As a substitute for providing a full custom ON condition for an existing relationship, the _orm.PropComparator.and_ function may be applied to a relationship attribute to augment additional criteria into the ON clause; the additional criteria will be combined with the default criteria using AND:

q = session.query(User).join(
    User.addresses.and_(Address.email_address != 'foo@bar.com')
)
New in version 1.4.

Joining to Tables and Subqueries

The target of a join may also be any table or SELECT statement, which may be related to a target entity or not. Use the appropriate .subquery() method in order to make a subquery out of a query:

subq = session.query(Address).\
    filter(Address.email_address == 'ed@foo.com').\
    subquery()


q = session.query(User).join(
    subq, User.id == subq.c.user_id
)

Joining to a subquery in terms of a specific relationship and/or target entity may be achieved by linking the subquery to the entity using _orm.aliased:

subq = session.query(Address).\
    filter(Address.email_address == 'ed@foo.com').\
    subquery()

address_subq = aliased(Address, subq)

q = session.query(User).join(
    User.addresses.of_type(address_subq)
)

Controlling what to Join From

In cases where the left side of the current state of _query.Query is not in line with what we want to join from, the _query.Query.select_from method may be used:

q = session.query(Address).select_from(User).\
                join(User.addresses).\
                filter(User.name == 'ed')

Which will produce SQL similar to:

SELECT address.* FROM user
    JOIN address ON user.id=address.user_id
    WHERE user.name = :name_1

Legacy Features of Query.join()

Deprecated since version 1.4: The following features are deprecated and will be removed in SQLAlchemy 2.0.

The _query.Query.join method currently supports several usage patterns and arguments that are considered to be legacy as of SQLAlchemy 1.3. A deprecation path will follow in the 1.4 series for the following features:

  • Joining on relationship names rather than attributes:

    session.query(User).join("addresses")
    

    Why it's legacy: the string name does not provide enough context for _query.Query.join to always know what is desired, notably in that there is no indication of what the left side of the join should be. This gives rise to flags like from_joinpoint as well as the ability to place several join clauses in a single _query.Query.join call which don't solve the problem fully while also adding new calling styles that are unnecessary and expensive to accommodate internally.

    Modern calling pattern: Use the actual relationship, e.g. User.addresses in the above case:

    session.query(User).join(User.addresses)
    
  • Automatic aliasing with the aliased=True flag:

    session.query(Node).join(Node.children, aliased=True).\
        filter(Node.name == 'some name')
    

    Why it's legacy: the automatic aliasing feature of _query.Query is intensely complicated, both in its internal implementation as well as in its observed behavior, and is almost never used. It is difficult to know upon inspection where and when its aliasing of a target entity, Node in the above case, will be applied and when it won't, and additionally the feature has to use very elaborate heuristics to achieve this implicit behavior.

    Modern calling pattern: Use the _orm.aliased construct explicitly:

    from sqlalchemy.orm import aliased
    
    n1 = aliased(Node)
    
    session.query(Node).join(Node.children.of_type(n1)).\
        filter(n1.name == 'some name')
    
  • Multiple joins in one call:

    session.query(User).join("orders", "items")
    
    session.query(User).join(User.orders, Order.items)
    
    session.query(User).join(
        (Order, User.orders),
        (Item, Item.order_id == Order.id)
    )
    
    session.query(User).join(Order, Item)
    
    # ... and several more forms actually
    

    Why it's legacy: being able to chain multiple ON clauses in one call to _query.Query.join is yet another attempt to solve the problem of being able to specify what entity to join from, and is the source of a large variety of potential calling patterns that are internally expensive and complicated to parse and accommodate.

    Modern calling pattern: Use relationship-bound attributes or SQL-oriented ON clauses within separate calls, so that each call to _query.Query.join knows what the left side should be:

    session.query(User).join(User.orders).join(
        Item, Item.order_id == Order.id)
    

See Also

:ref:`ormtutorial_joins` in the ORM tutorial.

:ref:`inheritance_toplevel` for details on how _query.Query.join is used for inheritance relationships.

_orm.join - a standalone ORM-level join function, used internally by _query.Query.join, which in previous SQLAlchemy versions was the primary ORM-level joining interface.

Parameters
targetUndocumented
*propsIncoming arguments for _query.Query.join, the props collection in modern use should be considered to be a one or two argument form, either as a single "target" entity or ORM attribute-bound relationship, or as a target entity plus an "on clause" which may be a SQL expression or ORM attribute-bound relationship.
**kwargsUndocumented
isouter=​FalseIf True, the join used will be a left outer join, just as if the _query.Query.outerjoin method were called.
full=​False

render FULL OUTER JOIN; implies isouter.

New in version 1.1.
from_joinpoint=​False

When using aliased=True, a setting of True here will cause the join to be from the most recent joined target, rather than starting back from the original FROM clauses of the query.

Note

This flag is considered legacy.

aliased=​False

If True, indicate that the JOIN target should be anonymously aliased. Subsequent calls to _query.Query.filter and similar will adapt the incoming criterion to the target alias, until _query.Query.reset_joinpoint is called.

Note

This flag is considered legacy.

def label(self, name):

Return the full SELECT statement represented by this _query.Query, converted to a scalar subquery with a label of the given name.

Analogous to sqlalchemy.sql.expression.SelectBase.label.

@_generative
@_assertions(_no_statement_condition)
def limit(self, limit):
Apply a LIMIT to the query and return the newly resulting Query.
@util.deprecated_20(':meth:`_orm.Query.merge_result`', alternative='The method is superseded by the :func:`_orm.merge_frozen_result` function.', becomes_legacy=True, enable_warnings=False)
def merge_result(self, iterator, load=True):

Merge a result into this _query.Query object's Session.

Given an iterator returned by a _query.Query of the same structure as this one, return an identical iterator of results, with all mapped instances merged into the session using .Session.merge. This is an optimized method which will merge all mapped instances, preserving the structure of the result rows and unmapped columns with less method overhead than that of calling .Session.merge explicitly for each value.

The structure of the results is determined based on the column list of this _query.Query - if these do not correspond, unchecked errors will occur.

The 'load' argument is the same as that of .Session.merge.

For an example of how _query.Query.merge_result is used, see the source code for the example :ref:`examples_caching`, where _query.Query.merge_result is used to efficiently restore state from a cache back into a target .Session.

@_generative
@_assertions(_no_statement_condition)
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 object identities are returned, or if multiple rows are returned for a query that returns only scalar values as opposed to full identity-mapped entities.

Calling .one results in an execution of the underlying query.

See Also

_query.Query.first

_query.Query.one_or_none

def one_or_none(self):

Return at most one result or raise an exception.

Returns None if the query selects no rows. Raises sqlalchemy.orm.exc.MultipleResultsFound if multiple object identities are returned, or if multiple rows are returned for a query that returns only scalar values as opposed to full identity-mapped entities.

Calling _query.Query.one_or_none results in an execution of the underlying query.

New in version 1.0.9: Added _query.Query.one_or_none

See Also

_query.Query.first

_query.Query.one

@_generative
def only_return_tuples(self, value):

When set to True, the query results will always be a tuple.

This is specifically for single element queries. The default is False.

New in version 1.2.5.

See Also

_query.Query.is_single_entity

@_generative
def options(self, *args):

Return a new _query.Query object, applying the given list of mapper options.

Most supplied options regard changing how column- and relationship-mapped attributes are loaded.

Apply one or more ORDER BY criteria to the query and return the newly resulting _query.Query.

e.g.:

q = session.query(Entity).order_by(Entity.id, Entity.name)

All existing ORDER BY criteria may be cancelled by passing None by itself. New ORDER BY criteria may then be added by invoking _orm.Query.order_by again, e.g.:

# will erase all ORDER BY and ORDER BY new_col alone
q = q.order_by(None).order_by(new_col)

See Also

These sections describe ORDER BY in terms of :term:`2.0 style` invocation but apply to _orm.Query as well:

:ref:`tutorial_order_by` - in the :ref:`unified_tutorial`

:ref:`tutorial_order_by_label` - in the :ref:`unified_tutorial`

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

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

Usage is the same as the join() method.

@_generative
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.

@_generative
def populate_existing(self):

Return a _query.Query that will expire and refresh all instances as they are loaded, or reused from the current .Session.

As of SQLAlchemy 1.4, the _orm.Query.populate_existing method is equivalent to using the populate_existing execution option at the ORM level. See the section :ref:`orm_queryguide_populate_existing` for further background on this option.

@_generative
@_assertions(_no_statement_condition)
def reset_joinpoint(self):

Return a new .Query, where the "join point" has been reset back to the base FROM entities of the query.

This method is usually used in conjunction with the aliased=True feature of the ~.Query.join method. See the example in ~.Query.join for how this is used.

def scalar(self):

Return the first element of the first result or None if no rows present. If multiple rows are returned, raises MultipleResultsFound.

>>> 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 scalar_subquery(self):

Return the full SELECT statement represented by this _query.Query, converted to a scalar subquery.

Analogous to sqlalchemy.sql.expression.SelectBase.scalar_subquery.

Changed in version 1.4: The _query.Query.scalar_subquery method replaces the _query.Query.as_scalar method.
@util.deprecated_20(':meth:`_orm.Query.select_entity_from`', alternative='Use the :func:`_orm.aliased` construct instead')
@_generative
@_assertions(_no_clauseelement_condition)
def select_entity_from(self, from_obj):

Set the FROM clause of this _query.Query to a core selectable, applying it as a replacement FROM clause for corresponding mapped entities.

The _query.Query.select_entity_from method supplies an alternative approach to the use case of applying an .aliased construct explicitly throughout a query. Instead of referring to the .aliased construct explicitly, _query.Query.select_entity_from automatically adapts all occurrences of the entity to the target selectable.

Given a case for .aliased such as selecting User objects from a SELECT statement:

select_stmt = select(User).where(User.id == 7)
user_alias = aliased(User, select_stmt)

q = session.query(user_alias).\
    filter(user_alias.name == 'ed')

Above, we apply the user_alias object explicitly throughout the query. When it's not feasible for user_alias to be referenced explicitly in many places, _query.Query.select_entity_from may be used at the start of the query to adapt the existing User entity:

q = session.query(User).\
    select_entity_from(select_stmt.subquery()).\
    filter(User.name == 'ed')

Above, the generated SQL will show that the User entity is adapted to our statement, even in the case of the WHERE clause:

SELECT anon_1.id AS anon_1_id, anon_1.name AS anon_1_name
FROM (SELECT "user".id AS id, "user".name AS name
FROM "user"
WHERE "user".id = :id_1) AS anon_1
WHERE anon_1.name = :name_1

The _query.Query.select_entity_from method is similar to the _query.Query.select_from method, in that it sets the FROM clause of the query. The difference is that it additionally applies adaptation to the other parts of the query that refer to the primary entity. If above we had used _query.Query.select_from instead, the SQL generated would have been:

-- uses plain select_from(), not select_entity_from()
SELECT "user".id AS user_id, "user".name AS user_name
FROM "user", (SELECT "user".id AS id, "user".name AS name
FROM "user"
WHERE "user".id = :id_1) AS anon_1
WHERE "user".name = :name_1

To supply textual SQL to the _query.Query.select_entity_from method, we can make use of the _expression.text construct. However, the _expression.text construct needs to be aligned with the columns of our entity, which is achieved by making use of the _expression.TextClause.columns method:

text_stmt = text("select id, name from user").columns(
    User.id, User.name).subquery()
q = session.query(User).select_entity_from(text_stmt)

_query.Query.select_entity_from itself accepts an .aliased object, so that the special options of .aliased such as :paramref:`.aliased.adapt_on_names` may be used within the scope of the _query.Query.select_entity_from method's adaptation services. Suppose a view user_view also returns rows from user. If we reflect this view into a _schema.Table, this view has no relationship to the _schema.Table to which we are mapped, however we can use name matching to select from it:

user_view = Table('user_view', metadata,
                  autoload_with=engine)
user_view_alias = aliased(
    User, user_view, adapt_on_names=True)
q = session.query(User).\
    select_entity_from(user_view_alias).\
    order_by(User.name)
Changed in version 1.1.7: The _query.Query.select_entity_from method now accepts an .aliased object as an alternative to a _expression.FromClause object.

See Also

_query.Query.select_from

Parameters
from​_obja _expression.FromClause object that will replace the FROM clause of this _query.Query. It also may be an instance of .aliased.
@_generative
@_assertions(_no_clauseelement_condition)
def select_from(self, *from_obj):

Set the FROM clause of this .Query explicitly.

.Query.select_from is often used in conjunction with .Query.join in order to control which entity is selected from on the "left" side of the join.

The entity or selectable object here effectively replaces the "left edge" of any calls to ~.Query.join, when no joinpoint is otherwise established - usually, the default "join point" is the leftmost entity in the ~.Query object's list of entities to be selected.

A typical example:

q = session.query(Address).select_from(User).\
    join(User.addresses).\
    filter(User.name == 'ed')

Which produces SQL equivalent to:

SELECT address.* FROM user
JOIN address ON user.id=address.user_id
WHERE user.name = :name_1
Changed in version 0.9: This method no longer applies the given FROM object to be the selectable from which matching entities select from; the .select_entity_from method now accomplishes this. See that method for a description of this behavior.

See Also

~.Query.join

.Query.select_entity_from

Parameters
*from​_objcollection of one or more entities to apply to the FROM clause. Entities can be mapped classes, .AliasedClass objects, .Mapper objects as well as core .FromClause elements like subqueries.
def set_label_style(self, style):

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.

Note

The _query.Query.set_label_style method only applies the output of _query.Query.statement, and not to any of the result-row invoking systems of _query.Query itself, e.g. _query.Query.first, _query.Query.all, etc. To execute a query using _query.Query.set_label_style, invoke the _query.Query.statement using .Session.execute:

result = session.execute(
    query
    .set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
    .statement
)
New in version 1.4.
@_generative
@_assertions(_no_statement_condition)
def slice(self, start, stop):

Computes the "slice" of the _query.Query represented by the given indices and returns the resulting _query.Query.

The start and stop indices behave like the argument to Python's built-in range function. This method provides an alternative to using LIMIT/OFFSET to get a slice of the query.

For example,

session.query(User).order_by(User.id).slice(1, 3)

renders as

SELECT users.id AS users_id,
       users.name AS users_name
FROM users ORDER BY users.id
LIMIT ? OFFSET ?
(2, 1)

See Also

_query.Query.limit

_query.Query.offset

def subquery(self, name=None, with_labels=False, reduce_columns=False):

Return the full SELECT statement represented by this _query.Query, embedded within an _expression.Alias.

Eager JOIN generation within the query is disabled.

Parameters
namestring name to be assigned as the alias; this is passed through to _expression.FromClause.alias. If None, a name will be deterministically generated at compile time.
with​_labelsif True, .with_labels will be called on the _query.Query first to apply table-qualified labels to all columns.
reduce​_columnsif True, _expression.Select.reduce_columns will be called on the resulting _expression.select construct, to remove same-named columns where one also refers to the other via foreign key or WHERE clause equivalence.
def union(self, *q):

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)

Note that many database backends do not allow ORDER BY to be rendered on a query called within UNION, EXCEPT, etc. To disable all ORDER BY clauses including those configured on mappers, issue query.order_by(None) - the resulting _query.Query object will not render ORDER BY within its SELECT statement.

def union_all(self, *q):

Produce a UNION ALL of this Query against one or more queries.

Works the same way as ~sqlalchemy.orm.query.Query.union. See that method for usage examples.

def update(self, values, synchronize_session='evaluate', update_args=None):

Perform an UPDATE with an arbitrary WHERE clause.

Updates rows matched by this query in the database.

E.g.:

sess.query(User).filter(User.age == 25).\
    update({User.age: User.age - 10}, synchronize_session=False)

sess.query(User).filter(User.age == 25).\
    update({"age": User.age - 10}, synchronize_session='evaluate')

Warning

See the section :ref:`orm_expression_update_delete` for important caveats and warnings, including limitations when using arbitrary UPDATE and DELETE with mapper inheritance configurations.

Parameters
valuesa dictionary with attributes names, or alternatively mapped attributes or SQL expressions, as keys, and literal values or sql expressions as values. If :ref:`parameter-ordered mode <updates_order_parameters>` is desired, the values can be passed as a list of 2-tuples; this requires that the :paramref:`~sqlalchemy.sql.expression.update.preserve_parameter_order` flag is passed to the :paramref:`.Query.update.update_args` dictionary as well.
synchronize​_sessionchooses the strategy to update the attributes on objects in the session. See the section :ref:`orm_expression_update_delete` for a discussion of these strategies.
update​_argsOptional dictionary, if present will be passed to the underlying _expression.update construct as the **kw for the object. May be used to pass dialect-specific arguments such as mysql_limit, as well as other special arguments such as :paramref:`~sqlalchemy.sql.expression.update.preserve_parameter_order`.
Returns
the count of rows matched as returned by the database's "row count" feature.
@util.deprecated('1.4', ':meth:`_query.Query.value` is deprecated and will be removed in a future release. Please use :meth:`_query.Query.with_entities` in combination with :meth:`_query.Query.scalar`')
def value(self, column):
Return a scalar result corresponding to the given column expression.
@util.deprecated('1.4', ':meth:`_query.Query.values` is deprecated and will be removed in a future release. Please use :meth:`_query.Query.with_entities`')
def values(self, *columns):
Return an iterator yielding result tuples corresponding to the given list of columns
def where(self, *criterion):

A synonym for .Query.filter.

New in version 1.4.
@_generative
def with_entities(self, *entities):

Return a new _query.Query replacing the SELECT list with the given entities.

e.g.:

# Users, filtered on some arbitrary criterion
# and then ordered by related email address
q = session.query(User).\
            join(User.address).\
            filter(User.name.like('%ed%')).\
            order_by(Address.email)

# given *only* User.id==5, Address.email, and 'q', what
# would the *next* User in the result be ?
subq = q.with_entities(Address.email).\
            order_by(None).\
            filter(User.id==5).\
            subquery()
q = q.join((subq, subq.c.email < Address.email)).\
            limit(1)
@_generative
def with_for_update(self, read=False, nowait=False, of=None, skip_locked=False, key_share=False):

return a new _query.Query with the specified options for the FOR UPDATE clause.

The behavior of this method is identical to that of _expression.GenerativeSelect.with_for_update. When called with no arguments, the resulting SELECT statement will have a FOR UPDATE clause appended. When additional arguments are specified, backend-specific options such as FOR UPDATE NOWAIT or LOCK IN SHARE MODE can take effect.

E.g.:

q = sess.query(User).populate_existing().with_for_update(nowait=True, of=User)

The above query on a PostgreSQL backend will render like:

SELECT users.id AS users_id FROM users FOR UPDATE OF users NOWAIT

Warning

Using with_for_update in the context of eager loading relationships is not officially supported or recommended by SQLAlchemy and may not work with certain queries on various database backends. When with_for_update is successfully used with a query that involves _orm.joinedload, SQLAlchemy will attempt to emit SQL that locks all involved tables.

Note

It is generally a good idea to combine the use of the _orm.Query.populate_existing method when using the _orm.Query.with_for_update method. The purpose of _orm.Query.populate_existing is to force all the data read from the SELECT to be populated into the ORM objects returned, even if these objects are already in the :term:`identity map`.

See Also

_expression.GenerativeSelect.with_for_update - Core level method with full argument and behavioral description.

_orm.Query.populate_existing - overwrites attributes of objects already loaded in the identity map.

@util.deprecated_20(':meth:`_orm.Query.with_labels` and :meth:`_orm.Query.apply_labels`', alternative='Use set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL) instead.')
def with_labels(self):

Undocumented

@util.deprecated_20(':meth:`_orm.Query.with_parent`', alternative='Use the :func:`_orm.with_parent` standalone construct.', becomes_legacy=True)
@util.preload_module('sqlalchemy.orm.relationships')
def with_parent(self, instance, property=None, from_entity=None):

Add filtering criterion that relates the given instance to a child object or collection, using its attribute state as well as an established _orm.relationship() configuration.

The method uses the .with_parent function to generate the clause, the result of which is passed to _query.Query.filter.

Parameters are the same as .with_parent, with the exception that the given property can be None, in which case a search is performed against this _query.Query object's target mapper.

Parameters
instanceAn instance which has some _orm.relationship.
propertyString property name, or class-bound attribute, which indicates what relationship from the instance should be used to reconcile the parent/child relationship.
from​_entityEntity in which to consider as the left side. This defaults to the "zero" entity of the _query.Query itself.
@_generative
@_assertions(_no_clauseelement_condition)
@util.deprecated_20(':meth:`_orm.Query.with_polymorphic`', alternative='Use the orm.with_polymorphic() standalone function')
def with_polymorphic(self, cls_or_mappers, selectable=None, polymorphic_on=None):

Load columns for inheriting classes.

This is a legacy method which is replaced by the _orm.with_polymorphic function.

Warning

The _orm.Query.with_polymorphic method does not support 1.4/2.0 style features including _orm.with_loader_criteria. Please migrate code to use _orm.with_polymorphic.

_query.Query.with_polymorphic applies transformations to the "main" mapped class represented by this _query.Query. The "main" mapped class here means the _query.Query object's first argument is a full class, i.e. session.query(SomeClass). These transformations allow additional tables to be present in the FROM clause so that columns for a joined-inheritance subclass are available in the query, both for the purposes of load-time efficiency as well as the ability to use these columns at query time.

See Also

:ref:`with_polymorphic` - illustrates current patterns

@_generative
def with_session(self, session):

Return a _query.Query that will use the given .Session.

While the _query.Query object is normally instantiated using the .Session.query method, it is legal to build the _query.Query directly without necessarily using a .Session. Such a _query.Query object, or any _query.Query already associated with a different .Session, can produce a new _query.Query object associated with a target session using this method:

from sqlalchemy.orm import Query

query = Query([MyClass]).filter(MyClass.id == 5)

result = query.with_session(my_session).one()
def with_transformation(self, fn):

Return a new _query.Query object transformed by the given function.

E.g.:

def filter_something(criterion):
    def transform(q):
        return q.filter(criterion)
    return transform

q = q.with_transformation(filter_something(x==5))

This allows ad-hoc recipes to be created for _query.Query objects. See the example at :ref:`hybrid_transformers`.

@_generative
def yield_per(self, count):

Yield only count rows at a time.

The purpose of this method is when fetching very large result sets (> 10K rows), to batch results in sub-collections and yield them out partially, so that the Python interpreter doesn't need to declare very large areas of memory which is both time consuming and leads to excessive memory use. The performance from fetching hundreds of thousands of rows can often double when a suitable yield-per setting (e.g. approximately 1000) is used, even with DBAPIs that buffer rows (which are most).

As of SQLAlchemy 1.4, the _orm.Query.yield_per method is equivalent to using the yield_per execution option at the ORM level. See the section :ref:`orm_queryguide_yield_per` for further background on this option.

_having_criteria: tuple =

Undocumented

_memoized_select_entities: tuple =

Undocumented

_setup_joins: tuple =

Undocumented

load_options =

Undocumented

_aliased_generation =

Undocumented

_aliased_generation_counter: int =

Undocumented

_auto_correlate: bool =

Undocumented

_compile_options =
_correlate: tuple =

Undocumented

_distinct: bool =

Undocumented

_distinct_on =

Undocumented

_enable_assertions =

Undocumented

_execution_options =
_for_update_arg =

Undocumented

_from_obj: tuple =

Undocumented

_group_by_clauses: tuple =

Undocumented

_label_style =

Undocumented

@util.memoized_property
_last_joined_entity =

Undocumented

_legacy_setup_joins: tuple =

Undocumented

_limit_clause =

Undocumented

_offset_clause =

Undocumented

_order_by_clauses: tuple =

Undocumented

_params =

Undocumented

_propagate_attrs =
_raw_columns =

Undocumented

_statement =

Undocumented

_where_criteria: tuple =

Undocumented

session =

Undocumented

@property
_current_path =

Undocumented

@property
_has_row_limiting_clause =

Undocumented

@property
column_descriptions =

Return metadata about the columns which would be returned by this _query.Query.

Format is a list of dictionaries:

user_alias = aliased(User, name='user2')
q = sess.query(User, User.id, user_alias)

# this expression:
q.column_descriptions

# would return:
[
    {
        'name':'User',
        'type':User,
        'aliased':False,
        'expr':User,
        'entity': User
    },
    {
        'name':'id',
        'type':Integer(),
        'aliased':False,
        'expr':User.id,
        'entity': User
    },
    {
        'name':'user2',
        'type':User,
        'aliased':True,
        'expr':user_alias,
        'entity': user_alias
    }
]
@property
get_label_style =

Retrieve the current label style.

New in version 1.4.
@property
is_single_entity =

Indicates if this _query.Query returns tuples or single entities.

Returns True if this query returns a single entity for each instance in its result list, and False if this query returns a tuple of entities for each result.

New in version 1.3.11.

See Also

_query.Query.only_return_tuples

@property
lazy_loaded_from =

An .InstanceState that is using this _query.Query for a lazy load operation.

Deprecated since version 1.4: This attribute should be viewed via the .ORMExecuteState.lazy_loaded_from attribute, within the context of the .SessionEvents.do_orm_execute event.

See Also

.ORMExecuteState.lazy_loaded_from

@property
selectable =

Return the _expression.Select object emitted by this _query.Query.

Used for _sa.inspect compatibility, this is equivalent to:

query.enable_eagerloads(False).with_labels().statement
@property
statement =

The full SELECT statement represented by this Query.

The statement by default will not have disambiguating labels applied to the construct unless with_labels(True) is called first.

@property
whereclause =

A readonly attribute which returns the current WHERE criterion for this Query.

This returned value is a SQL expression construct, or None if no criterion has been established.