From bcc6829fcc8e71acbd93d9c848a9f7d792af9004 Mon Sep 17 00:00:00 2001 From: Mike Bayer Date: Wed, 8 Feb 2017 17:47:29 -0500 Subject: [PATCH] - document Query.with_session(), direct constructor usage Change-Id: I47499d040623202dd9b3be0ea65f2d9ad03c11a4 (cherry picked from commit 7db699163bed203d8060f06097e1489eea7ba079) --- lib/sqlalchemy/orm/query.py | 45 +++++++++++++++++++++++++++++++++++-- 1 file changed, 43 insertions(+), 2 deletions(-) diff --git a/lib/sqlalchemy/orm/query.py b/lib/sqlalchemy/orm/query.py index 3e9dba4436..992d295d4a 100644 --- a/lib/sqlalchemy/orm/query.py +++ b/lib/sqlalchemy/orm/query.py @@ -59,8 +59,12 @@ class Query(object): criteria and options associated with it. :class:`.Query` objects are normally initially generated using the - :meth:`~.Session.query` method of :class:`.Session`. For a full - walkthrough of :class:`.Query` usage, see the + :meth:`~.Session.query` method of :class:`.Session`, and in + less common cases by instantiating the :class:`.Query` directly and + associating with a :class:`.Session` using the :meth:`.Query.with_session` + method. + + For a full walkthrough of :class:`.Query` usage, see the :ref:`ormtutorial_toplevel`. """ @@ -105,6 +109,30 @@ class Query(object): _current_path = _path_registry def __init__(self, entities, session=None): + """Construct a :class:`.Query` directly. + + E.g.:: + + q = Query([User, Address], session=some_session) + + The above is equivalent to:: + + q = some_session.query(User, Address) + + :param entities: a sequence of entities and/or SQL expressions. + + :param session: a :class:`.Session` with which the :class:`.Query` + will be associated. Optional; a :class:`.Query` can be associated + with a :class:`.Session` generatively via the + :meth:`.Query.with_session` method as well. + + .. seealso:: + + :meth:`.Session.query` + + :meth:`.Query.with_session` + + """ self.session = session self._polymorphic_adapters = {} self._set_entities(entities) @@ -978,6 +1006,19 @@ class Query(object): def with_session(self, session): """Return a :class:`.Query` that will use the given :class:`.Session`. + While the :class:`.Query` object is normally instantiated using the + :meth:`.Session.query` method, it is legal to build the :class:`.Query` + directly without necessarily using a :class:`.Session`. Such a + :class:`.Query` object, or any :class:`.Query` already associated + with a different :class:`.Session`, can produce a new :class:`.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() + """ self.session = session -- 2.47.2