Return the :class:`_query.Query` object for use as a subquery. This method should be used within the lambda callable being used to generate a step of an enclosing :class:`.BakedQuery`. The parameter should normally be the :class:`_query.Query` object that is passed
(self, query_or_session)
| 246 | return query, statement |
| 247 | |
| 248 | def to_query(self, query_or_session): |
| 249 | """Return the :class:`_query.Query` object for use as a subquery. |
| 250 | |
| 251 | This method should be used within the lambda callable being used |
| 252 | to generate a step of an enclosing :class:`.BakedQuery`. The |
| 253 | parameter should normally be the :class:`_query.Query` object that |
| 254 | is passed to the lambda:: |
| 255 | |
| 256 | sub_bq = self.bakery(lambda s: s.query(User.name)) |
| 257 | sub_bq += lambda q: q.filter(User.id == Address.user_id).correlate(Address) |
| 258 | |
| 259 | main_bq = self.bakery(lambda s: s.query(Address)) |
| 260 | main_bq += lambda q: q.filter(sub_bq.to_query(q).exists()) |
| 261 | |
| 262 | In the case where the subquery is used in the first callable against |
| 263 | a :class:`.Session`, the :class:`.Session` is also accepted:: |
| 264 | |
| 265 | sub_bq = self.bakery(lambda s: s.query(User.name)) |
| 266 | sub_bq += lambda q: q.filter(User.id == Address.user_id).correlate(Address) |
| 267 | |
| 268 | main_bq = self.bakery( |
| 269 | lambda s: s.query(Address.id, sub_bq.to_query(q).scalar_subquery()) |
| 270 | ) |
| 271 | |
| 272 | :param query_or_session: a :class:`_query.Query` object or a class |
| 273 | :class:`.Session` object, that is assumed to be within the context |
| 274 | of an enclosing :class:`.BakedQuery` callable. |
| 275 | |
| 276 | """ # noqa: E501 |
| 277 | |
| 278 | if isinstance(query_or_session, Session): |
| 279 | session = query_or_session |
| 280 | elif isinstance(query_or_session, Query): |
| 281 | session = query_or_session.session |
| 282 | if session is None: |
| 283 | raise sa_exc.ArgumentError( |
| 284 | "Given Query needs to be associated with a Session" |
| 285 | ) |
| 286 | else: |
| 287 | raise TypeError( |
| 288 | "Query or Session object expected, got %r." |
| 289 | % type(query_or_session) |
| 290 | ) |
| 291 | return self._as_query(session) |
| 292 | |
| 293 | def _as_query(self, session): |
| 294 | query = self.steps[0](session) |