Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/sqlalchemy/orm/_orm_constructors.py: 60%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

128 statements  

1# orm/_orm_constructors.py 

2# Copyright (C) 2005-2025 the SQLAlchemy authors and contributors 

3# <see AUTHORS file> 

4# 

5# This module is part of SQLAlchemy and is released under 

6# the MIT License: https://www.opensource.org/licenses/mit-license.php 

7 

8from __future__ import annotations 

9 

10import typing 

11from typing import Any 

12from typing import Callable 

13from typing import Collection 

14from typing import Iterable 

15from typing import NoReturn 

16from typing import Optional 

17from typing import overload 

18from typing import Type 

19from typing import TYPE_CHECKING 

20from typing import Union 

21 

22from . import mapperlib as mapperlib 

23from ._typing import _O 

24from .descriptor_props import Composite 

25from .descriptor_props import Synonym 

26from .interfaces import _AttributeOptions 

27from .properties import MappedColumn 

28from .properties import MappedSQLExpression 

29from .query import AliasOption 

30from .relationships import _RelationshipArgumentType 

31from .relationships import _RelationshipBackPopulatesArgument 

32from .relationships import _RelationshipDeclared 

33from .relationships import _RelationshipSecondaryArgument 

34from .relationships import RelationshipProperty 

35from .session import Session 

36from .util import _ORMJoin 

37from .util import AliasedClass 

38from .util import AliasedInsp 

39from .util import LoaderCriteriaOption 

40from .. import sql 

41from .. import util 

42from ..exc import InvalidRequestError 

43from ..sql._typing import _no_kw 

44from ..sql.base import _NoArg 

45from ..sql.base import SchemaEventTarget 

46from ..sql.schema import _InsertSentinelColumnDefault 

47from ..sql.schema import SchemaConst 

48from ..sql.selectable import FromClause 

49from ..util.typing import Annotated 

50from ..util.typing import Literal 

51 

52if TYPE_CHECKING: 

53 from ._typing import _EntityType 

54 from ._typing import _ORMColumnExprArgument 

55 from .descriptor_props import _CC 

56 from .descriptor_props import _CompositeAttrType 

57 from .interfaces import PropComparator 

58 from .mapper import Mapper 

59 from .query import Query 

60 from .relationships import _LazyLoadArgumentType 

61 from .relationships import _ORMColCollectionArgument 

62 from .relationships import _ORMOrderByArgument 

63 from .relationships import _RelationshipJoinConditionArgument 

64 from .relationships import ORMBackrefArgument 

65 from .session import _SessionBind 

66 from ..sql._typing import _AutoIncrementType 

67 from ..sql._typing import _ColumnExpressionArgument 

68 from ..sql._typing import _FromClauseArgument 

69 from ..sql._typing import _InfoType 

70 from ..sql._typing import _OnClauseArgument 

71 from ..sql._typing import _TypeEngineArgument 

72 from ..sql.elements import ColumnElement 

73 from ..sql.schema import _ServerDefaultArgument 

74 from ..sql.schema import _ServerOnUpdateArgument 

75 from ..sql.selectable import Alias 

76 from ..sql.selectable import Subquery 

77 

78 

79_T = typing.TypeVar("_T") 

80 

81 

82@util.deprecated( 

83 "1.4", 

84 "The :class:`.AliasOption` object is not necessary " 

85 "for entities to be matched up to a query that is established " 

86 "via :meth:`.Query.from_statement` and now does nothing.", 

87 enable_warnings=False, # AliasOption itself warns 

88) 

89def contains_alias(alias: Union[Alias, Subquery]) -> AliasOption: 

90 r"""Return a :class:`.MapperOption` that will indicate to the 

91 :class:`_query.Query` 

92 that the main table has been aliased. 

93 

94 """ 

95 return AliasOption(alias) 

96 

97 

98def mapped_column( 

99 __name_pos: Optional[ 

100 Union[str, _TypeEngineArgument[Any], SchemaEventTarget] 

101 ] = None, 

102 __type_pos: Optional[ 

103 Union[_TypeEngineArgument[Any], SchemaEventTarget] 

104 ] = None, 

105 /, 

106 *args: SchemaEventTarget, 

107 init: Union[_NoArg, bool] = _NoArg.NO_ARG, 

108 repr: Union[_NoArg, bool] = _NoArg.NO_ARG, # noqa: A002 

109 default: Optional[Any] = _NoArg.NO_ARG, 

110 default_factory: Union[_NoArg, Callable[[], _T]] = _NoArg.NO_ARG, 

111 compare: Union[_NoArg, bool] = _NoArg.NO_ARG, 

112 kw_only: Union[_NoArg, bool] = _NoArg.NO_ARG, 

113 hash: Union[_NoArg, bool, None] = _NoArg.NO_ARG, # noqa: A002 

114 nullable: Optional[ 

115 Union[bool, Literal[SchemaConst.NULL_UNSPECIFIED]] 

116 ] = SchemaConst.NULL_UNSPECIFIED, 

117 primary_key: Optional[bool] = False, 

118 deferred: Union[_NoArg, bool] = _NoArg.NO_ARG, 

119 deferred_group: Optional[str] = None, 

120 deferred_raiseload: Optional[bool] = None, 

121 use_existing_column: bool = False, 

122 name: Optional[str] = None, 

123 type_: Optional[_TypeEngineArgument[Any]] = None, 

124 autoincrement: _AutoIncrementType = "auto", 

125 doc: Optional[str] = None, 

126 key: Optional[str] = None, 

127 index: Optional[bool] = None, 

128 unique: Optional[bool] = None, 

129 info: Optional[_InfoType] = None, 

130 onupdate: Optional[Any] = None, 

131 insert_default: Optional[Any] = _NoArg.NO_ARG, 

132 server_default: Optional[_ServerDefaultArgument] = None, 

133 server_onupdate: Optional[_ServerOnUpdateArgument] = None, 

134 active_history: bool = False, 

135 quote: Optional[bool] = None, 

136 system: bool = False, 

137 comment: Optional[str] = None, 

138 sort_order: Union[_NoArg, int] = _NoArg.NO_ARG, 

139 **kw: Any, 

140) -> MappedColumn[Any]: 

141 r"""declare a new ORM-mapped :class:`_schema.Column` construct 

142 for use within :ref:`Declarative Table <orm_declarative_table>` 

143 configuration. 

144 

145 The :func:`_orm.mapped_column` function provides an ORM-aware and 

146 Python-typing-compatible construct which is used with 

147 :ref:`declarative <orm_declarative_mapping>` mappings to indicate an 

148 attribute that's mapped to a Core :class:`_schema.Column` object. It 

149 provides the equivalent feature as mapping an attribute to a 

150 :class:`_schema.Column` object directly when using Declarative, 

151 specifically when using :ref:`Declarative Table <orm_declarative_table>` 

152 configuration. 

153 

154 .. versionadded:: 2.0 

155 

156 :func:`_orm.mapped_column` is normally used with explicit typing along with 

157 the :class:`_orm.Mapped` annotation type, where it can derive the SQL 

158 type and nullability for the column based on what's present within the 

159 :class:`_orm.Mapped` annotation. It also may be used without annotations 

160 as a drop-in replacement for how :class:`_schema.Column` is used in 

161 Declarative mappings in SQLAlchemy 1.x style. 

162 

163 For usage examples of :func:`_orm.mapped_column`, see the documentation 

164 at :ref:`orm_declarative_table`. 

165 

166 .. seealso:: 

167 

168 :ref:`orm_declarative_table` - complete documentation 

169 

170 :ref:`whatsnew_20_orm_declarative_typing` - migration notes for 

171 Declarative mappings using 1.x style mappings 

172 

173 :param __name: String name to give to the :class:`_schema.Column`. This 

174 is an optional, positional only argument that if present must be the 

175 first positional argument passed. If omitted, the attribute name to 

176 which the :func:`_orm.mapped_column` is mapped will be used as the SQL 

177 column name. 

178 :param __type: :class:`_types.TypeEngine` type or instance which will 

179 indicate the datatype to be associated with the :class:`_schema.Column`. 

180 This is an optional, positional-only argument that if present must 

181 immediately follow the ``__name`` parameter if present also, or otherwise 

182 be the first positional parameter. If omitted, the ultimate type for 

183 the column may be derived either from the annotated type, or if a 

184 :class:`_schema.ForeignKey` is present, from the datatype of the 

185 referenced column. 

186 :param \*args: Additional positional arguments include constructs such 

187 as :class:`_schema.ForeignKey`, :class:`_schema.CheckConstraint`, 

188 and :class:`_schema.Identity`, which are passed through to the constructed 

189 :class:`_schema.Column`. 

190 :param nullable: Optional bool, whether the column should be "NULL" or 

191 "NOT NULL". If omitted, the nullability is derived from the type 

192 annotation based on whether or not ``typing.Optional`` is present. 

193 ``nullable`` defaults to ``True`` otherwise for non-primary key columns, 

194 and ``False`` for primary key columns. 

195 :param primary_key: optional bool, indicates the :class:`_schema.Column` 

196 would be part of the table's primary key or not. 

197 :param deferred: Optional bool - this keyword argument is consumed by the 

198 ORM declarative process, and is not part of the :class:`_schema.Column` 

199 itself; instead, it indicates that this column should be "deferred" for 

200 loading as though mapped by :func:`_orm.deferred`. 

201 

202 .. seealso:: 

203 

204 :ref:`orm_queryguide_deferred_declarative` 

205 

206 :param deferred_group: Implies :paramref:`_orm.mapped_column.deferred` 

207 to ``True``, and set the :paramref:`_orm.deferred.group` parameter. 

208 

209 .. seealso:: 

210 

211 :ref:`orm_queryguide_deferred_group` 

212 

213 :param deferred_raiseload: Implies :paramref:`_orm.mapped_column.deferred` 

214 to ``True``, and set the :paramref:`_orm.deferred.raiseload` parameter. 

215 

216 .. seealso:: 

217 

218 :ref:`orm_queryguide_deferred_raiseload` 

219 

220 :param use_existing_column: if True, will attempt to locate the given 

221 column name on an inherited superclass (typically single inheriting 

222 superclass), and if present, will not produce a new column, mapping 

223 to the superclass column as though it were omitted from this class. 

224 This is used for mixins that add new columns to an inherited superclass. 

225 

226 .. seealso:: 

227 

228 :ref:`orm_inheritance_column_conflicts` 

229 

230 .. versionadded:: 2.0.0b4 

231 

232 :param default: Passed directly to the 

233 :paramref:`_schema.Column.default` parameter if the 

234 :paramref:`_orm.mapped_column.insert_default` parameter is not present. 

235 Additionally, when used with :ref:`orm_declarative_native_dataclasses`, 

236 indicates a default Python value that should be applied to the keyword 

237 constructor within the generated ``__init__()`` method. 

238 

239 Note that in the case of dataclass generation when 

240 :paramref:`_orm.mapped_column.insert_default` is not present, this means 

241 the :paramref:`_orm.mapped_column.default` value is used in **two** 

242 places, both the ``__init__()`` method as well as the 

243 :paramref:`_schema.Column.default` parameter. While this behavior may 

244 change in a future release, for the moment this tends to "work out"; a 

245 default of ``None`` will mean that the :class:`_schema.Column` gets no 

246 default generator, whereas a default that refers to a non-``None`` Python 

247 or SQL expression value will be assigned up front on the object when 

248 ``__init__()`` is called, which is the same value that the Core 

249 :class:`_sql.Insert` construct would use in any case, leading to the same 

250 end result. 

251 

252 .. note:: When using Core level column defaults that are callables to 

253 be interpreted by the underlying :class:`_schema.Column` in conjunction 

254 with :ref:`ORM-mapped dataclasses 

255 <orm_declarative_native_dataclasses>`, especially those that are 

256 :ref:`context-aware default functions <context_default_functions>`, 

257 **the** :paramref:`_orm.mapped_column.insert_default` **parameter must 

258 be used instead**. This is necessary to disambiguate the callable from 

259 being interpreted as a dataclass level default. 

260 

261 .. seealso:: 

262 

263 :ref:`defaults_default_factory_insert_default` 

264 

265 :paramref:`_orm.mapped_column.insert_default` 

266 

267 :paramref:`_orm.mapped_column.default_factory` 

268 

269 :param insert_default: Passed directly to the 

270 :paramref:`_schema.Column.default` parameter; will supersede the value 

271 of :paramref:`_orm.mapped_column.default` when present, however 

272 :paramref:`_orm.mapped_column.default` will always apply to the 

273 constructor default for a dataclasses mapping. 

274 

275 .. seealso:: 

276 

277 :ref:`defaults_default_factory_insert_default` 

278 

279 :paramref:`_orm.mapped_column.default` 

280 

281 :paramref:`_orm.mapped_column.default_factory` 

282 

283 :param sort_order: An integer that indicates how this mapped column 

284 should be sorted compared to the others when the ORM is creating a 

285 :class:`_schema.Table`. Among mapped columns that have the same 

286 value the default ordering is used, placing first the mapped columns 

287 defined in the main class, then the ones in the super classes. 

288 Defaults to 0. The sort is ascending. 

289 

290 .. versionadded:: 2.0.4 

291 

292 :param active_history=False: 

293 

294 When ``True``, indicates that the "previous" value for a 

295 scalar attribute should be loaded when replaced, if not 

296 already loaded. Normally, history tracking logic for 

297 simple non-primary-key scalar values only needs to be 

298 aware of the "new" value in order to perform a flush. This 

299 flag is available for applications that make use of 

300 :func:`.attributes.get_history` or :meth:`.Session.is_modified` 

301 which also need to know the "previous" value of the attribute. 

302 

303 .. versionadded:: 2.0.10 

304 

305 

306 :param init: Specific to :ref:`orm_declarative_native_dataclasses`, 

307 specifies if the mapped attribute should be part of the ``__init__()`` 

308 method as generated by the dataclass process. 

309 :param repr: Specific to :ref:`orm_declarative_native_dataclasses`, 

310 specifies if the mapped attribute should be part of the ``__repr__()`` 

311 method as generated by the dataclass process. 

312 :param default_factory: Specific to 

313 :ref:`orm_declarative_native_dataclasses`, 

314 specifies a default-value generation function that will take place 

315 as part of the ``__init__()`` 

316 method as generated by the dataclass process. 

317 

318 .. seealso:: 

319 

320 :ref:`defaults_default_factory_insert_default` 

321 

322 :paramref:`_orm.mapped_column.default` 

323 

324 :paramref:`_orm.mapped_column.insert_default` 

325 

326 :param compare: Specific to 

327 :ref:`orm_declarative_native_dataclasses`, indicates if this field 

328 should be included in comparison operations when generating the 

329 ``__eq__()`` and ``__ne__()`` methods for the mapped class. 

330 

331 .. versionadded:: 2.0.0b4 

332 

333 :param kw_only: Specific to 

334 :ref:`orm_declarative_native_dataclasses`, indicates if this field 

335 should be marked as keyword-only when generating the ``__init__()``. 

336 

337 :param hash: Specific to 

338 :ref:`orm_declarative_native_dataclasses`, controls if this field 

339 is included when generating the ``__hash__()`` method for the mapped 

340 class. 

341 

342 .. versionadded:: 2.0.36 

343 

344 :param \**kw: All remaining keyword arguments are passed through to the 

345 constructor for the :class:`_schema.Column`. 

346 

347 """ 

348 

349 return MappedColumn( 

350 __name_pos, 

351 __type_pos, 

352 *args, 

353 name=name, 

354 type_=type_, 

355 autoincrement=autoincrement, 

356 insert_default=insert_default, 

357 attribute_options=_AttributeOptions( 

358 init, repr, default, default_factory, compare, kw_only, hash 

359 ), 

360 doc=doc, 

361 key=key, 

362 index=index, 

363 unique=unique, 

364 info=info, 

365 active_history=active_history, 

366 nullable=nullable, 

367 onupdate=onupdate, 

368 primary_key=primary_key, 

369 server_default=server_default, 

370 server_onupdate=server_onupdate, 

371 use_existing_column=use_existing_column, 

372 quote=quote, 

373 comment=comment, 

374 system=system, 

375 deferred=deferred, 

376 deferred_group=deferred_group, 

377 deferred_raiseload=deferred_raiseload, 

378 sort_order=sort_order, 

379 **kw, 

380 ) 

381 

382 

383def orm_insert_sentinel( 

384 name: Optional[str] = None, 

385 type_: Optional[_TypeEngineArgument[Any]] = None, 

386 *, 

387 default: Optional[Any] = None, 

388 omit_from_statements: bool = True, 

389) -> MappedColumn[Any]: 

390 """Provides a surrogate :func:`_orm.mapped_column` that generates 

391 a so-called :term:`sentinel` column, allowing efficient bulk 

392 inserts with deterministic RETURNING sorting for tables that don't 

393 otherwise have qualifying primary key configurations. 

394 

395 Use of :func:`_orm.orm_insert_sentinel` is analogous to the use of the 

396 :func:`_schema.insert_sentinel` construct within a Core 

397 :class:`_schema.Table` construct. 

398 

399 Guidelines for adding this construct to a Declarative mapped class 

400 are the same as that of the :func:`_schema.insert_sentinel` construct; 

401 the database table itself also needs to have a column with this name 

402 present. 

403 

404 For background on how this object is used, see the section 

405 :ref:`engine_insertmanyvalues_sentinel_columns` as part of the 

406 section :ref:`engine_insertmanyvalues`. 

407 

408 .. seealso:: 

409 

410 :func:`_schema.insert_sentinel` 

411 

412 :ref:`engine_insertmanyvalues` 

413 

414 :ref:`engine_insertmanyvalues_sentinel_columns` 

415 

416 

417 .. versionadded:: 2.0.10 

418 

419 """ 

420 

421 return mapped_column( 

422 name=name, 

423 default=( 

424 default if default is not None else _InsertSentinelColumnDefault() 

425 ), 

426 _omit_from_statements=omit_from_statements, 

427 insert_sentinel=True, 

428 use_existing_column=True, 

429 nullable=True, 

430 ) 

431 

432 

433@util.deprecated_params( 

434 **{ 

435 arg: ( 

436 "2.0", 

437 f"The :paramref:`_orm.column_property.{arg}` parameter is " 

438 "deprecated for :func:`_orm.column_property`. This parameter " 

439 "applies to a writeable-attribute in a Declarative Dataclasses " 

440 "configuration only, and :func:`_orm.column_property` is treated " 

441 "as a read-only attribute in this context.", 

442 ) 

443 for arg in ("init", "kw_only", "default", "default_factory") 

444 } 

445) 

446def column_property( 

447 column: _ORMColumnExprArgument[_T], 

448 *additional_columns: _ORMColumnExprArgument[Any], 

449 group: Optional[str] = None, 

450 deferred: bool = False, 

451 raiseload: bool = False, 

452 comparator_factory: Optional[Type[PropComparator[_T]]] = None, 

453 init: Union[_NoArg, bool] = _NoArg.NO_ARG, 

454 repr: Union[_NoArg, bool] = _NoArg.NO_ARG, # noqa: A002 

455 default: Optional[Any] = _NoArg.NO_ARG, 

456 default_factory: Union[_NoArg, Callable[[], _T]] = _NoArg.NO_ARG, 

457 compare: Union[_NoArg, bool] = _NoArg.NO_ARG, 

458 kw_only: Union[_NoArg, bool] = _NoArg.NO_ARG, 

459 hash: Union[_NoArg, bool, None] = _NoArg.NO_ARG, # noqa: A002 

460 active_history: bool = False, 

461 expire_on_flush: bool = True, 

462 info: Optional[_InfoType] = None, 

463 doc: Optional[str] = None, 

464) -> MappedSQLExpression[_T]: 

465 r"""Provide a column-level property for use with a mapping. 

466 

467 With Declarative mappings, :func:`_orm.column_property` is used to 

468 map read-only SQL expressions to a mapped class. 

469 

470 When using Imperative mappings, :func:`_orm.column_property` also 

471 takes on the role of mapping table columns with additional features. 

472 When using fully Declarative mappings, the :func:`_orm.mapped_column` 

473 construct should be used for this purpose. 

474 

475 With Declarative Dataclass mappings, :func:`_orm.column_property` 

476 is considered to be **read only**, and will not be included in the 

477 Dataclass ``__init__()`` constructor. 

478 

479 The :func:`_orm.column_property` function returns an instance of 

480 :class:`.ColumnProperty`. 

481 

482 .. seealso:: 

483 

484 :ref:`mapper_column_property_sql_expressions` - general use of 

485 :func:`_orm.column_property` to map SQL expressions 

486 

487 :ref:`orm_imperative_table_column_options` - usage of 

488 :func:`_orm.column_property` with Imperative Table mappings to apply 

489 additional options to a plain :class:`_schema.Column` object 

490 

491 :param \*cols: 

492 list of Column objects to be mapped. 

493 

494 :param active_history=False: 

495 

496 Used only for Imperative Table mappings, or legacy-style Declarative 

497 mappings (i.e. which have not been upgraded to 

498 :func:`_orm.mapped_column`), for column-based attributes that are 

499 expected to be writeable; use :func:`_orm.mapped_column` with 

500 :paramref:`_orm.mapped_column.active_history` for Declarative mappings. 

501 See that parameter for functional details. 

502 

503 :param comparator_factory: a class which extends 

504 :class:`.ColumnProperty.Comparator` which provides custom SQL 

505 clause generation for comparison operations. 

506 

507 :param group: 

508 a group name for this property when marked as deferred. 

509 

510 :param deferred: 

511 when True, the column property is "deferred", meaning that 

512 it does not load immediately, and is instead loaded when the 

513 attribute is first accessed on an instance. See also 

514 :func:`~sqlalchemy.orm.deferred`. 

515 

516 :param doc: 

517 optional string that will be applied as the doc on the 

518 class-bound descriptor. 

519 

520 :param expire_on_flush=True: 

521 Disable expiry on flush. A column_property() which refers 

522 to a SQL expression (and not a single table-bound column) 

523 is considered to be a "read only" property; populating it 

524 has no effect on the state of data, and it can only return 

525 database state. For this reason a column_property()'s value 

526 is expired whenever the parent object is involved in a 

527 flush, that is, has any kind of "dirty" state within a flush. 

528 Setting this parameter to ``False`` will have the effect of 

529 leaving any existing value present after the flush proceeds. 

530 Note that the :class:`.Session` with default expiration 

531 settings still expires 

532 all attributes after a :meth:`.Session.commit` call, however. 

533 

534 :param info: Optional data dictionary which will be populated into the 

535 :attr:`.MapperProperty.info` attribute of this object. 

536 

537 :param raiseload: if True, indicates the column should raise an error 

538 when undeferred, rather than loading the value. This can be 

539 altered at query time by using the :func:`.deferred` option with 

540 raiseload=False. 

541 

542 .. versionadded:: 1.4 

543 

544 .. seealso:: 

545 

546 :ref:`orm_queryguide_deferred_raiseload` 

547 

548 :param init: Specific to :ref:`orm_declarative_native_dataclasses`, 

549 specifies if the mapped attribute should be part of the ``__init__()`` 

550 method as generated by the dataclass process. 

551 :param repr: Specific to :ref:`orm_declarative_native_dataclasses`, 

552 specifies if the mapped attribute should be part of the ``__repr__()`` 

553 method as generated by the dataclass process. 

554 :param default_factory: Specific to 

555 :ref:`orm_declarative_native_dataclasses`, 

556 specifies a default-value generation function that will take place 

557 as part of the ``__init__()`` 

558 method as generated by the dataclass process. 

559 

560 .. seealso:: 

561 

562 :ref:`defaults_default_factory_insert_default` 

563 

564 :paramref:`_orm.mapped_column.default` 

565 

566 :paramref:`_orm.mapped_column.insert_default` 

567 

568 :param compare: Specific to 

569 :ref:`orm_declarative_native_dataclasses`, indicates if this field 

570 should be included in comparison operations when generating the 

571 ``__eq__()`` and ``__ne__()`` methods for the mapped class. 

572 

573 .. versionadded:: 2.0.0b4 

574 

575 :param kw_only: Specific to 

576 :ref:`orm_declarative_native_dataclasses`, indicates if this field 

577 should be marked as keyword-only when generating the ``__init__()``. 

578 

579 :param hash: Specific to 

580 :ref:`orm_declarative_native_dataclasses`, controls if this field 

581 is included when generating the ``__hash__()`` method for the mapped 

582 class. 

583 

584 .. versionadded:: 2.0.36 

585 

586 """ 

587 return MappedSQLExpression( 

588 column, 

589 *additional_columns, 

590 attribute_options=_AttributeOptions( 

591 False if init is _NoArg.NO_ARG else init, 

592 repr, 

593 default, 

594 default_factory, 

595 compare, 

596 kw_only, 

597 hash, 

598 ), 

599 group=group, 

600 deferred=deferred, 

601 raiseload=raiseload, 

602 comparator_factory=comparator_factory, 

603 active_history=active_history, 

604 expire_on_flush=expire_on_flush, 

605 info=info, 

606 doc=doc, 

607 _assume_readonly_dc_attributes=True, 

608 ) 

609 

610 

611@overload 

612def composite( 

613 _class_or_attr: _CompositeAttrType[Any], 

614 /, 

615 *attrs: _CompositeAttrType[Any], 

616 group: Optional[str] = None, 

617 deferred: bool = False, 

618 raiseload: bool = False, 

619 comparator_factory: Optional[Type[Composite.Comparator[_T]]] = None, 

620 active_history: bool = False, 

621 init: Union[_NoArg, bool] = _NoArg.NO_ARG, 

622 repr: Union[_NoArg, bool] = _NoArg.NO_ARG, # noqa: A002 

623 default: Optional[Any] = _NoArg.NO_ARG, 

624 default_factory: Union[_NoArg, Callable[[], _T]] = _NoArg.NO_ARG, 

625 compare: Union[_NoArg, bool] = _NoArg.NO_ARG, 

626 kw_only: Union[_NoArg, bool] = _NoArg.NO_ARG, 

627 hash: Union[_NoArg, bool, None] = _NoArg.NO_ARG, # noqa: A002 

628 info: Optional[_InfoType] = None, 

629 doc: Optional[str] = None, 

630 **__kw: Any, 

631) -> Composite[Any]: ... 

632 

633 

634@overload 

635def composite( 

636 _class_or_attr: Type[_CC], 

637 /, 

638 *attrs: _CompositeAttrType[Any], 

639 group: Optional[str] = None, 

640 deferred: bool = False, 

641 raiseload: bool = False, 

642 comparator_factory: Optional[Type[Composite.Comparator[_T]]] = None, 

643 active_history: bool = False, 

644 init: Union[_NoArg, bool] = _NoArg.NO_ARG, 

645 repr: Union[_NoArg, bool] = _NoArg.NO_ARG, # noqa: A002 

646 default: Optional[Any] = _NoArg.NO_ARG, 

647 default_factory: Union[_NoArg, Callable[[], _T]] = _NoArg.NO_ARG, 

648 compare: Union[_NoArg, bool] = _NoArg.NO_ARG, 

649 kw_only: Union[_NoArg, bool] = _NoArg.NO_ARG, 

650 hash: Union[_NoArg, bool, None] = _NoArg.NO_ARG, # noqa: A002 

651 info: Optional[_InfoType] = None, 

652 doc: Optional[str] = None, 

653 **__kw: Any, 

654) -> Composite[_CC]: ... 

655 

656 

657@overload 

658def composite( 

659 _class_or_attr: Callable[..., _CC], 

660 /, 

661 *attrs: _CompositeAttrType[Any], 

662 group: Optional[str] = None, 

663 deferred: bool = False, 

664 raiseload: bool = False, 

665 comparator_factory: Optional[Type[Composite.Comparator[_T]]] = None, 

666 active_history: bool = False, 

667 init: Union[_NoArg, bool] = _NoArg.NO_ARG, 

668 repr: Union[_NoArg, bool] = _NoArg.NO_ARG, # noqa: A002 

669 default: Optional[Any] = _NoArg.NO_ARG, 

670 default_factory: Union[_NoArg, Callable[[], _T]] = _NoArg.NO_ARG, 

671 compare: Union[_NoArg, bool] = _NoArg.NO_ARG, 

672 kw_only: Union[_NoArg, bool] = _NoArg.NO_ARG, 

673 hash: Union[_NoArg, bool, None] = _NoArg.NO_ARG, # noqa: A002 

674 info: Optional[_InfoType] = None, 

675 doc: Optional[str] = None, 

676 **__kw: Any, 

677) -> Composite[_CC]: ... 

678 

679 

680def composite( 

681 _class_or_attr: Union[ 

682 None, Type[_CC], Callable[..., _CC], _CompositeAttrType[Any] 

683 ] = None, 

684 /, 

685 *attrs: _CompositeAttrType[Any], 

686 group: Optional[str] = None, 

687 deferred: bool = False, 

688 raiseload: bool = False, 

689 comparator_factory: Optional[Type[Composite.Comparator[_T]]] = None, 

690 active_history: bool = False, 

691 init: Union[_NoArg, bool] = _NoArg.NO_ARG, 

692 repr: Union[_NoArg, bool] = _NoArg.NO_ARG, # noqa: A002 

693 default: Optional[Any] = _NoArg.NO_ARG, 

694 default_factory: Union[_NoArg, Callable[[], _T]] = _NoArg.NO_ARG, 

695 compare: Union[_NoArg, bool] = _NoArg.NO_ARG, 

696 kw_only: Union[_NoArg, bool] = _NoArg.NO_ARG, 

697 hash: Union[_NoArg, bool, None] = _NoArg.NO_ARG, # noqa: A002 

698 info: Optional[_InfoType] = None, 

699 doc: Optional[str] = None, 

700 **__kw: Any, 

701) -> Composite[Any]: 

702 r"""Return a composite column-based property for use with a Mapper. 

703 

704 See the mapping documentation section :ref:`mapper_composite` for a 

705 full usage example. 

706 

707 The :class:`.MapperProperty` returned by :func:`.composite` 

708 is the :class:`.Composite`. 

709 

710 :param class\_: 

711 The "composite type" class, or any classmethod or callable which 

712 will produce a new instance of the composite object given the 

713 column values in order. 

714 

715 :param \*attrs: 

716 List of elements to be mapped, which may include: 

717 

718 * :class:`_schema.Column` objects 

719 * :func:`_orm.mapped_column` constructs 

720 * string names of other attributes on the mapped class, which may be 

721 any other SQL or object-mapped attribute. This can for 

722 example allow a composite that refers to a many-to-one relationship 

723 

724 :param active_history=False: 

725 When ``True``, indicates that the "previous" value for a 

726 scalar attribute should be loaded when replaced, if not 

727 already loaded. See the same flag on :func:`.column_property`. 

728 

729 :param group: 

730 A group name for this property when marked as deferred. 

731 

732 :param deferred: 

733 When True, the column property is "deferred", meaning that it does 

734 not load immediately, and is instead loaded when the attribute is 

735 first accessed on an instance. See also 

736 :func:`~sqlalchemy.orm.deferred`. 

737 

738 :param comparator_factory: a class which extends 

739 :class:`.Composite.Comparator` which provides custom SQL 

740 clause generation for comparison operations. 

741 

742 :param doc: 

743 optional string that will be applied as the doc on the 

744 class-bound descriptor. 

745 

746 :param info: Optional data dictionary which will be populated into the 

747 :attr:`.MapperProperty.info` attribute of this object. 

748 

749 :param init: Specific to :ref:`orm_declarative_native_dataclasses`, 

750 specifies if the mapped attribute should be part of the ``__init__()`` 

751 method as generated by the dataclass process. 

752 :param repr: Specific to :ref:`orm_declarative_native_dataclasses`, 

753 specifies if the mapped attribute should be part of the ``__repr__()`` 

754 method as generated by the dataclass process. 

755 :param default_factory: Specific to 

756 :ref:`orm_declarative_native_dataclasses`, 

757 specifies a default-value generation function that will take place 

758 as part of the ``__init__()`` 

759 method as generated by the dataclass process. 

760 

761 :param compare: Specific to 

762 :ref:`orm_declarative_native_dataclasses`, indicates if this field 

763 should be included in comparison operations when generating the 

764 ``__eq__()`` and ``__ne__()`` methods for the mapped class. 

765 

766 .. versionadded:: 2.0.0b4 

767 

768 :param kw_only: Specific to 

769 :ref:`orm_declarative_native_dataclasses`, indicates if this field 

770 should be marked as keyword-only when generating the ``__init__()``. 

771 

772 :param hash: Specific to 

773 :ref:`orm_declarative_native_dataclasses`, controls if this field 

774 is included when generating the ``__hash__()`` method for the mapped 

775 class. 

776 

777 .. versionadded:: 2.0.36 

778 """ 

779 if __kw: 

780 raise _no_kw() 

781 

782 return Composite( 

783 _class_or_attr, 

784 *attrs, 

785 attribute_options=_AttributeOptions( 

786 init, repr, default, default_factory, compare, kw_only, hash 

787 ), 

788 group=group, 

789 deferred=deferred, 

790 raiseload=raiseload, 

791 comparator_factory=comparator_factory, 

792 active_history=active_history, 

793 info=info, 

794 doc=doc, 

795 ) 

796 

797 

798def with_loader_criteria( 

799 entity_or_base: _EntityType[Any], 

800 where_criteria: Union[ 

801 _ColumnExpressionArgument[bool], 

802 Callable[[Any], _ColumnExpressionArgument[bool]], 

803 ], 

804 loader_only: bool = False, 

805 include_aliases: bool = False, 

806 propagate_to_loaders: bool = True, 

807 track_closure_variables: bool = True, 

808) -> LoaderCriteriaOption: 

809 """Add additional WHERE criteria to the load for all occurrences of 

810 a particular entity. 

811 

812 .. versionadded:: 1.4 

813 

814 The :func:`_orm.with_loader_criteria` option is intended to add 

815 limiting criteria to a particular kind of entity in a query, 

816 **globally**, meaning it will apply to the entity as it appears 

817 in the SELECT query as well as within any subqueries, join 

818 conditions, and relationship loads, including both eager and lazy 

819 loaders, without the need for it to be specified in any particular 

820 part of the query. The rendering logic uses the same system used by 

821 single table inheritance to ensure a certain discriminator is applied 

822 to a table. 

823 

824 E.g., using :term:`2.0-style` queries, we can limit the way the 

825 ``User.addresses`` collection is loaded, regardless of the kind 

826 of loading used:: 

827 

828 from sqlalchemy.orm import with_loader_criteria 

829 

830 stmt = select(User).options( 

831 selectinload(User.addresses), 

832 with_loader_criteria(Address, Address.email_address != "foo"), 

833 ) 

834 

835 Above, the "selectinload" for ``User.addresses`` will apply the 

836 given filtering criteria to the WHERE clause. 

837 

838 Another example, where the filtering will be applied to the 

839 ON clause of the join, in this example using :term:`1.x style` 

840 queries:: 

841 

842 q = ( 

843 session.query(User) 

844 .outerjoin(User.addresses) 

845 .options(with_loader_criteria(Address, Address.email_address != "foo")) 

846 ) 

847 

848 The primary purpose of :func:`_orm.with_loader_criteria` is to use 

849 it in the :meth:`_orm.SessionEvents.do_orm_execute` event handler 

850 to ensure that all occurrences of a particular entity are filtered 

851 in a certain way, such as filtering for access control roles. It 

852 also can be used to apply criteria to relationship loads. In the 

853 example below, we can apply a certain set of rules to all queries 

854 emitted by a particular :class:`_orm.Session`:: 

855 

856 session = Session(bind=engine) 

857 

858 

859 @event.listens_for("do_orm_execute", session) 

860 def _add_filtering_criteria(execute_state): 

861 

862 if ( 

863 execute_state.is_select 

864 and not execute_state.is_column_load 

865 and not execute_state.is_relationship_load 

866 ): 

867 execute_state.statement = execute_state.statement.options( 

868 with_loader_criteria( 

869 SecurityRole, 

870 lambda cls: cls.role.in_(["some_role"]), 

871 include_aliases=True, 

872 ) 

873 ) 

874 

875 In the above example, the :meth:`_orm.SessionEvents.do_orm_execute` 

876 event will intercept all queries emitted using the 

877 :class:`_orm.Session`. For those queries which are SELECT statements 

878 and are not attribute or relationship loads a custom 

879 :func:`_orm.with_loader_criteria` option is added to the query. The 

880 :func:`_orm.with_loader_criteria` option will be used in the given 

881 statement and will also be automatically propagated to all relationship 

882 loads that descend from this query. 

883 

884 The criteria argument given is a ``lambda`` that accepts a ``cls`` 

885 argument. The given class will expand to include all mapped subclass 

886 and need not itself be a mapped class. 

887 

888 .. tip:: 

889 

890 When using :func:`_orm.with_loader_criteria` option in 

891 conjunction with the :func:`_orm.contains_eager` loader option, 

892 it's important to note that :func:`_orm.with_loader_criteria` only 

893 affects the part of the query that determines what SQL is rendered 

894 in terms of the WHERE and FROM clauses. The 

895 :func:`_orm.contains_eager` option does not affect the rendering of 

896 the SELECT statement outside of the columns clause, so does not have 

897 any interaction with the :func:`_orm.with_loader_criteria` option. 

898 However, the way things "work" is that :func:`_orm.contains_eager` 

899 is meant to be used with a query that is already selecting from the 

900 additional entities in some way, where 

901 :func:`_orm.with_loader_criteria` can apply it's additional 

902 criteria. 

903 

904 In the example below, assuming a mapping relationship as 

905 ``A -> A.bs -> B``, the given :func:`_orm.with_loader_criteria` 

906 option will affect the way in which the JOIN is rendered:: 

907 

908 stmt = ( 

909 select(A) 

910 .join(A.bs) 

911 .options(contains_eager(A.bs), with_loader_criteria(B, B.flag == 1)) 

912 ) 

913 

914 Above, the given :func:`_orm.with_loader_criteria` option will 

915 affect the ON clause of the JOIN that is specified by 

916 ``.join(A.bs)``, so is applied as expected. The 

917 :func:`_orm.contains_eager` option has the effect that columns from 

918 ``B`` are added to the columns clause: 

919 

920 .. sourcecode:: sql 

921 

922 SELECT 

923 b.id, b.a_id, b.data, b.flag, 

924 a.id AS id_1, 

925 a.data AS data_1 

926 FROM a JOIN b ON a.id = b.a_id AND b.flag = :flag_1 

927 

928 

929 The use of the :func:`_orm.contains_eager` option within the above 

930 statement has no effect on the behavior of the 

931 :func:`_orm.with_loader_criteria` option. If the 

932 :func:`_orm.contains_eager` option were omitted, the SQL would be 

933 the same as regards the FROM and WHERE clauses, where 

934 :func:`_orm.with_loader_criteria` continues to add its criteria to 

935 the ON clause of the JOIN. The addition of 

936 :func:`_orm.contains_eager` only affects the columns clause, in that 

937 additional columns against ``b`` are added which are then consumed 

938 by the ORM to produce ``B`` instances. 

939 

940 .. warning:: The use of a lambda inside of the call to 

941 :func:`_orm.with_loader_criteria` is only invoked **once per unique 

942 class**. Custom functions should not be invoked within this lambda. 

943 See :ref:`engine_lambda_caching` for an overview of the "lambda SQL" 

944 feature, which is for advanced use only. 

945 

946 :param entity_or_base: a mapped class, or a class that is a super 

947 class of a particular set of mapped classes, to which the rule 

948 will apply. 

949 

950 :param where_criteria: a Core SQL expression that applies limiting 

951 criteria. This may also be a "lambda:" or Python function that 

952 accepts a target class as an argument, when the given class is 

953 a base with many different mapped subclasses. 

954 

955 .. note:: To support pickling, use a module-level Python function to 

956 produce the SQL expression instead of a lambda or a fixed SQL 

957 expression, which tend to not be picklable. 

958 

959 :param include_aliases: if True, apply the rule to :func:`_orm.aliased` 

960 constructs as well. 

961 

962 :param propagate_to_loaders: defaults to True, apply to relationship 

963 loaders such as lazy loaders. This indicates that the 

964 option object itself including SQL expression is carried along with 

965 each loaded instance. Set to ``False`` to prevent the object from 

966 being assigned to individual instances. 

967 

968 

969 .. seealso:: 

970 

971 :ref:`examples_session_orm_events` - includes examples of using 

972 :func:`_orm.with_loader_criteria`. 

973 

974 :ref:`do_orm_execute_global_criteria` - basic example on how to 

975 combine :func:`_orm.with_loader_criteria` with the 

976 :meth:`_orm.SessionEvents.do_orm_execute` event. 

977 

978 :param track_closure_variables: when False, closure variables inside 

979 of a lambda expression will not be used as part of 

980 any cache key. This allows more complex expressions to be used 

981 inside of a lambda expression but requires that the lambda ensures 

982 it returns the identical SQL every time given a particular class. 

983 

984 .. versionadded:: 1.4.0b2 

985 

986 """ # noqa: E501 

987 return LoaderCriteriaOption( 

988 entity_or_base, 

989 where_criteria, 

990 loader_only, 

991 include_aliases, 

992 propagate_to_loaders, 

993 track_closure_variables, 

994 ) 

995 

996 

997def relationship( 

998 argument: Optional[_RelationshipArgumentType[Any]] = None, 

999 secondary: Optional[_RelationshipSecondaryArgument] = None, 

1000 *, 

1001 uselist: Optional[bool] = None, 

1002 collection_class: Optional[ 

1003 Union[Type[Collection[Any]], Callable[[], Collection[Any]]] 

1004 ] = None, 

1005 primaryjoin: Optional[_RelationshipJoinConditionArgument] = None, 

1006 secondaryjoin: Optional[_RelationshipJoinConditionArgument] = None, 

1007 back_populates: Optional[_RelationshipBackPopulatesArgument] = None, 

1008 order_by: _ORMOrderByArgument = False, 

1009 backref: Optional[ORMBackrefArgument] = None, 

1010 overlaps: Optional[str] = None, 

1011 post_update: bool = False, 

1012 cascade: str = "save-update, merge", 

1013 viewonly: bool = False, 

1014 init: Union[_NoArg, bool] = _NoArg.NO_ARG, 

1015 repr: Union[_NoArg, bool] = _NoArg.NO_ARG, # noqa: A002 

1016 default: Union[_NoArg, _T] = _NoArg.NO_ARG, 

1017 default_factory: Union[_NoArg, Callable[[], _T]] = _NoArg.NO_ARG, 

1018 compare: Union[_NoArg, bool] = _NoArg.NO_ARG, 

1019 kw_only: Union[_NoArg, bool] = _NoArg.NO_ARG, 

1020 hash: Union[_NoArg, bool, None] = _NoArg.NO_ARG, # noqa: A002 

1021 lazy: _LazyLoadArgumentType = "select", 

1022 passive_deletes: Union[Literal["all"], bool] = False, 

1023 passive_updates: bool = True, 

1024 active_history: bool = False, 

1025 enable_typechecks: bool = True, 

1026 foreign_keys: Optional[_ORMColCollectionArgument] = None, 

1027 remote_side: Optional[_ORMColCollectionArgument] = None, 

1028 join_depth: Optional[int] = None, 

1029 comparator_factory: Optional[ 

1030 Type[RelationshipProperty.Comparator[Any]] 

1031 ] = None, 

1032 single_parent: bool = False, 

1033 innerjoin: bool = False, 

1034 distinct_target_key: Optional[bool] = None, 

1035 load_on_pending: bool = False, 

1036 query_class: Optional[Type[Query[Any]]] = None, 

1037 info: Optional[_InfoType] = None, 

1038 omit_join: Literal[None, False] = None, 

1039 sync_backref: Optional[bool] = None, 

1040 **kw: Any, 

1041) -> _RelationshipDeclared[Any]: 

1042 """Provide a relationship between two mapped classes. 

1043 

1044 This corresponds to a parent-child or associative table relationship. 

1045 The constructed class is an instance of :class:`.Relationship`. 

1046 

1047 .. seealso:: 

1048 

1049 :ref:`tutorial_orm_related_objects` - tutorial introduction 

1050 to :func:`_orm.relationship` in the :ref:`unified_tutorial` 

1051 

1052 :ref:`relationship_config_toplevel` - narrative documentation 

1053 

1054 :param argument: 

1055 This parameter refers to the class that is to be related. It 

1056 accepts several forms, including a direct reference to the target 

1057 class itself, the :class:`_orm.Mapper` instance for the target class, 

1058 a Python callable / lambda that will return a reference to the 

1059 class or :class:`_orm.Mapper` when called, and finally a string 

1060 name for the class, which will be resolved from the 

1061 :class:`_orm.registry` in use in order to locate the class, e.g.:: 

1062 

1063 class SomeClass(Base): 

1064 # ... 

1065 

1066 related = relationship("RelatedClass") 

1067 

1068 The :paramref:`_orm.relationship.argument` may also be omitted from the 

1069 :func:`_orm.relationship` construct entirely, and instead placed inside 

1070 a :class:`_orm.Mapped` annotation on the left side, which should 

1071 include a Python collection type if the relationship is expected 

1072 to be a collection, such as:: 

1073 

1074 class SomeClass(Base): 

1075 # ... 

1076 

1077 related_items: Mapped[List["RelatedItem"]] = relationship() 

1078 

1079 Or for a many-to-one or one-to-one relationship:: 

1080 

1081 class SomeClass(Base): 

1082 # ... 

1083 

1084 related_item: Mapped["RelatedItem"] = relationship() 

1085 

1086 .. seealso:: 

1087 

1088 :ref:`orm_declarative_properties` - further detail 

1089 on relationship configuration when using Declarative. 

1090 

1091 :param secondary: 

1092 For a many-to-many relationship, specifies the intermediary 

1093 table, and is typically an instance of :class:`_schema.Table`. 

1094 In less common circumstances, the argument may also be specified 

1095 as an :class:`_expression.Alias` construct, or even a 

1096 :class:`_expression.Join` construct. 

1097 

1098 :paramref:`_orm.relationship.secondary` may 

1099 also be passed as a callable function which is evaluated at 

1100 mapper initialization time. When using Declarative, it may also 

1101 be a string argument noting the name of a :class:`_schema.Table` 

1102 that is 

1103 present in the :class:`_schema.MetaData` 

1104 collection associated with the 

1105 parent-mapped :class:`_schema.Table`. 

1106 

1107 .. versionchanged:: 2.1 When passed as a string, the argument is 

1108 interpreted as a string name that should exist directly in the 

1109 registry of tables. The Python ``eval()`` function is no longer 

1110 used for the :paramref:`_orm.relationship.secondary` argument when 

1111 passed as a string. 

1112 

1113 The :paramref:`_orm.relationship.secondary` keyword argument is 

1114 typically applied in the case where the intermediary 

1115 :class:`_schema.Table` 

1116 is not otherwise expressed in any direct class mapping. If the 

1117 "secondary" table is also explicitly mapped elsewhere (e.g. as in 

1118 :ref:`association_pattern`), one should consider applying the 

1119 :paramref:`_orm.relationship.viewonly` flag so that this 

1120 :func:`_orm.relationship` 

1121 is not used for persistence operations which 

1122 may conflict with those of the association object pattern. 

1123 

1124 .. seealso:: 

1125 

1126 :ref:`relationships_many_to_many` - Reference example of "many 

1127 to many". 

1128 

1129 :ref:`self_referential_many_to_many` - Specifics on using 

1130 many-to-many in a self-referential case. 

1131 

1132 :ref:`declarative_many_to_many` - Additional options when using 

1133 Declarative. 

1134 

1135 :ref:`association_pattern` - an alternative to 

1136 :paramref:`_orm.relationship.secondary` 

1137 when composing association 

1138 table relationships, allowing additional attributes to be 

1139 specified on the association table. 

1140 

1141 :ref:`composite_secondary_join` - a lesser-used pattern which 

1142 in some cases can enable complex :func:`_orm.relationship` SQL 

1143 conditions to be used. 

1144 

1145 :param active_history=False: 

1146 When ``True``, indicates that the "previous" value for a 

1147 many-to-one reference should be loaded when replaced, if 

1148 not already loaded. Normally, history tracking logic for 

1149 simple many-to-ones only needs to be aware of the "new" 

1150 value in order to perform a flush. This flag is available 

1151 for applications that make use of 

1152 :func:`.attributes.get_history` which also need to know 

1153 the "previous" value of the attribute. 

1154 

1155 :param backref: 

1156 A reference to a string relationship name, or a :func:`_orm.backref` 

1157 construct, which will be used to automatically generate a new 

1158 :func:`_orm.relationship` on the related class, which then refers to this 

1159 one using a bi-directional :paramref:`_orm.relationship.back_populates` 

1160 configuration. 

1161 

1162 In modern Python, explicit use of :func:`_orm.relationship` 

1163 with :paramref:`_orm.relationship.back_populates` should be preferred, 

1164 as it is more robust in terms of mapper configuration as well as 

1165 more conceptually straightforward. It also integrates with 

1166 new :pep:`484` typing features introduced in SQLAlchemy 2.0 which 

1167 is not possible with dynamically generated attributes. 

1168 

1169 .. seealso:: 

1170 

1171 :ref:`relationships_backref` - notes on using 

1172 :paramref:`_orm.relationship.backref` 

1173 

1174 :ref:`tutorial_orm_related_objects` - in the :ref:`unified_tutorial`, 

1175 presents an overview of bi-directional relationship configuration 

1176 and behaviors using :paramref:`_orm.relationship.back_populates` 

1177 

1178 :func:`.backref` - allows control over :func:`_orm.relationship` 

1179 configuration when using :paramref:`_orm.relationship.backref`. 

1180 

1181 

1182 :param back_populates: 

1183 Indicates the name of a :func:`_orm.relationship` on the related 

1184 class that will be synchronized with this one. It is usually 

1185 expected that the :func:`_orm.relationship` on the related class 

1186 also refer to this one. This allows objects on both sides of 

1187 each :func:`_orm.relationship` to synchronize in-Python state 

1188 changes and also provides directives to the :term:`unit of work` 

1189 flush process how changes along these relationships should 

1190 be persisted. 

1191 

1192 .. seealso:: 

1193 

1194 :ref:`tutorial_orm_related_objects` - in the :ref:`unified_tutorial`, 

1195 presents an overview of bi-directional relationship configuration 

1196 and behaviors. 

1197 

1198 :ref:`relationship_patterns` - includes many examples of 

1199 :paramref:`_orm.relationship.back_populates`. 

1200 

1201 :paramref:`_orm.relationship.backref` - legacy form which allows 

1202 more succinct configuration, but does not support explicit typing 

1203 

1204 :param overlaps: 

1205 A string name or comma-delimited set of names of other relationships 

1206 on either this mapper, a descendant mapper, or a target mapper with 

1207 which this relationship may write to the same foreign keys upon 

1208 persistence. The only effect this has is to eliminate the 

1209 warning that this relationship will conflict with another upon 

1210 persistence. This is used for such relationships that are truly 

1211 capable of conflicting with each other on write, but the application 

1212 will ensure that no such conflicts occur. 

1213 

1214 .. versionadded:: 1.4 

1215 

1216 .. seealso:: 

1217 

1218 :ref:`error_qzyx` - usage example 

1219 

1220 :param cascade: 

1221 A comma-separated list of cascade rules which determines how 

1222 Session operations should be "cascaded" from parent to child. 

1223 This defaults to ``False``, which means the default cascade 

1224 should be used - this default cascade is ``"save-update, merge"``. 

1225 

1226 The available cascades are ``save-update``, ``merge``, 

1227 ``expunge``, ``delete``, ``delete-orphan``, and ``refresh-expire``. 

1228 An additional option, ``all`` indicates shorthand for 

1229 ``"save-update, merge, refresh-expire, 

1230 expunge, delete"``, and is often used as in ``"all, delete-orphan"`` 

1231 to indicate that related objects should follow along with the 

1232 parent object in all cases, and be deleted when de-associated. 

1233 

1234 .. seealso:: 

1235 

1236 :ref:`unitofwork_cascades` - Full detail on each of the available 

1237 cascade options. 

1238 

1239 :param cascade_backrefs=False: 

1240 Legacy; this flag is always False. 

1241 

1242 .. versionchanged:: 2.0 "cascade_backrefs" functionality has been 

1243 removed. 

1244 

1245 :param collection_class: 

1246 A class or callable that returns a new list-holding object. will 

1247 be used in place of a plain list for storing elements. 

1248 

1249 .. seealso:: 

1250 

1251 :ref:`custom_collections` - Introductory documentation and 

1252 examples. 

1253 

1254 :param comparator_factory: 

1255 A class which extends :class:`.Relationship.Comparator` 

1256 which provides custom SQL clause generation for comparison 

1257 operations. 

1258 

1259 .. seealso:: 

1260 

1261 :class:`.PropComparator` - some detail on redefining comparators 

1262 at this level. 

1263 

1264 :ref:`custom_comparators` - Brief intro to this feature. 

1265 

1266 

1267 :param distinct_target_key=None: 

1268 Indicate if a "subquery" eager load should apply the DISTINCT 

1269 keyword to the innermost SELECT statement. When left as ``None``, 

1270 the DISTINCT keyword will be applied in those cases when the target 

1271 columns do not comprise the full primary key of the target table. 

1272 When set to ``True``, the DISTINCT keyword is applied to the 

1273 innermost SELECT unconditionally. 

1274 

1275 It may be desirable to set this flag to False when the DISTINCT is 

1276 reducing performance of the innermost subquery beyond that of what 

1277 duplicate innermost rows may be causing. 

1278 

1279 .. seealso:: 

1280 

1281 :ref:`loading_toplevel` - includes an introduction to subquery 

1282 eager loading. 

1283 

1284 :param doc: 

1285 Docstring which will be applied to the resulting descriptor. 

1286 

1287 :param foreign_keys: 

1288 

1289 A list of columns which are to be used as "foreign key" 

1290 columns, or columns which refer to the value in a remote 

1291 column, within the context of this :func:`_orm.relationship` 

1292 object's :paramref:`_orm.relationship.primaryjoin` condition. 

1293 That is, if the :paramref:`_orm.relationship.primaryjoin` 

1294 condition of this :func:`_orm.relationship` is ``a.id == 

1295 b.a_id``, and the values in ``b.a_id`` are required to be 

1296 present in ``a.id``, then the "foreign key" column of this 

1297 :func:`_orm.relationship` is ``b.a_id``. 

1298 

1299 In normal cases, the :paramref:`_orm.relationship.foreign_keys` 

1300 parameter is **not required.** :func:`_orm.relationship` will 

1301 automatically determine which columns in the 

1302 :paramref:`_orm.relationship.primaryjoin` condition are to be 

1303 considered "foreign key" columns based on those 

1304 :class:`_schema.Column` objects that specify 

1305 :class:`_schema.ForeignKey`, 

1306 or are otherwise listed as referencing columns in a 

1307 :class:`_schema.ForeignKeyConstraint` construct. 

1308 :paramref:`_orm.relationship.foreign_keys` is only needed when: 

1309 

1310 1. There is more than one way to construct a join from the local 

1311 table to the remote table, as there are multiple foreign key 

1312 references present. Setting ``foreign_keys`` will limit the 

1313 :func:`_orm.relationship` 

1314 to consider just those columns specified 

1315 here as "foreign". 

1316 

1317 2. The :class:`_schema.Table` being mapped does not actually have 

1318 :class:`_schema.ForeignKey` or 

1319 :class:`_schema.ForeignKeyConstraint` 

1320 constructs present, often because the table 

1321 was reflected from a database that does not support foreign key 

1322 reflection (MySQL MyISAM). 

1323 

1324 3. The :paramref:`_orm.relationship.primaryjoin` 

1325 argument is used to 

1326 construct a non-standard join condition, which makes use of 

1327 columns or expressions that do not normally refer to their 

1328 "parent" column, such as a join condition expressed by a 

1329 complex comparison using a SQL function. 

1330 

1331 The :func:`_orm.relationship` construct will raise informative 

1332 error messages that suggest the use of the 

1333 :paramref:`_orm.relationship.foreign_keys` parameter when 

1334 presented with an ambiguous condition. In typical cases, 

1335 if :func:`_orm.relationship` doesn't raise any exceptions, the 

1336 :paramref:`_orm.relationship.foreign_keys` parameter is usually 

1337 not needed. 

1338 

1339 :paramref:`_orm.relationship.foreign_keys` may also be passed as a 

1340 callable function which is evaluated at mapper initialization time, 

1341 and may be passed as a Python-evaluable string when using 

1342 Declarative. 

1343 

1344 .. warning:: When passed as a Python-evaluable string, the 

1345 argument is interpreted using Python's ``eval()`` function. 

1346 **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**. 

1347 See :ref:`declarative_relationship_eval` for details on 

1348 declarative evaluation of :func:`_orm.relationship` arguments. 

1349 

1350 .. seealso:: 

1351 

1352 :ref:`relationship_foreign_keys` 

1353 

1354 :ref:`relationship_custom_foreign` 

1355 

1356 :func:`.foreign` - allows direct annotation of the "foreign" 

1357 columns within a :paramref:`_orm.relationship.primaryjoin` 

1358 condition. 

1359 

1360 :param info: Optional data dictionary which will be populated into the 

1361 :attr:`.MapperProperty.info` attribute of this object. 

1362 

1363 :param innerjoin=False: 

1364 When ``True``, joined eager loads will use an inner join to join 

1365 against related tables instead of an outer join. The purpose 

1366 of this option is generally one of performance, as inner joins 

1367 generally perform better than outer joins. 

1368 

1369 This flag can be set to ``True`` when the relationship references an 

1370 object via many-to-one using local foreign keys that are not 

1371 nullable, or when the reference is one-to-one or a collection that 

1372 is guaranteed to have one or at least one entry. 

1373 

1374 The option supports the same "nested" and "unnested" options as 

1375 that of :paramref:`_orm.joinedload.innerjoin`. See that flag 

1376 for details on nested / unnested behaviors. 

1377 

1378 .. seealso:: 

1379 

1380 :paramref:`_orm.joinedload.innerjoin` - the option as specified by 

1381 loader option, including detail on nesting behavior. 

1382 

1383 :ref:`what_kind_of_loading` - Discussion of some details of 

1384 various loader options. 

1385 

1386 

1387 :param join_depth: 

1388 When non-``None``, an integer value indicating how many levels 

1389 deep "eager" loaders should join on a self-referring or cyclical 

1390 relationship. The number counts how many times the same Mapper 

1391 shall be present in the loading condition along a particular join 

1392 branch. When left at its default of ``None``, eager loaders 

1393 will stop chaining when they encounter a the same target mapper 

1394 which is already higher up in the chain. This option applies 

1395 both to joined- and subquery- eager loaders. 

1396 

1397 .. seealso:: 

1398 

1399 :ref:`self_referential_eager_loading` - Introductory documentation 

1400 and examples. 

1401 

1402 :param lazy='select': specifies 

1403 How the related items should be loaded. Default value is 

1404 ``select``. Values include: 

1405 

1406 * ``select`` - items should be loaded lazily when the property is 

1407 first accessed, using a separate SELECT statement, or identity map 

1408 fetch for simple many-to-one references. 

1409 

1410 * ``immediate`` - items should be loaded as the parents are loaded, 

1411 using a separate SELECT statement, or identity map fetch for 

1412 simple many-to-one references. 

1413 

1414 * ``joined`` - items should be loaded "eagerly" in the same query as 

1415 that of the parent, using a JOIN or LEFT OUTER JOIN. Whether 

1416 the join is "outer" or not is determined by the 

1417 :paramref:`_orm.relationship.innerjoin` parameter. 

1418 

1419 * ``subquery`` - items should be loaded "eagerly" as the parents are 

1420 loaded, using one additional SQL statement, which issues a JOIN to 

1421 a subquery of the original statement, for each collection 

1422 requested. 

1423 

1424 * ``selectin`` - items should be loaded "eagerly" as the parents 

1425 are loaded, using one or more additional SQL statements, which 

1426 issues a JOIN to the immediate parent object, specifying primary 

1427 key identifiers using an IN clause. 

1428 

1429 * ``raise`` - lazy loading is disallowed; accessing 

1430 the attribute, if its value were not already loaded via eager 

1431 loading, will raise an :exc:`~sqlalchemy.exc.InvalidRequestError`. 

1432 This strategy can be used when objects are to be detached from 

1433 their attached :class:`.Session` after they are loaded. 

1434 

1435 * ``raise_on_sql`` - lazy loading that emits SQL is disallowed; 

1436 accessing the attribute, if its value were not already loaded via 

1437 eager loading, will raise an 

1438 :exc:`~sqlalchemy.exc.InvalidRequestError`, **if the lazy load 

1439 needs to emit SQL**. If the lazy load can pull the related value 

1440 from the identity map or determine that it should be None, the 

1441 value is loaded. This strategy can be used when objects will 

1442 remain associated with the attached :class:`.Session`, however 

1443 additional SELECT statements should be blocked. 

1444 

1445 * ``write_only`` - the attribute will be configured with a special 

1446 "virtual collection" that may receive 

1447 :meth:`_orm.WriteOnlyCollection.add` and 

1448 :meth:`_orm.WriteOnlyCollection.remove` commands to add or remove 

1449 individual objects, but will not under any circumstances load or 

1450 iterate the full set of objects from the database directly. Instead, 

1451 methods such as :meth:`_orm.WriteOnlyCollection.select`, 

1452 :meth:`_orm.WriteOnlyCollection.insert`, 

1453 :meth:`_orm.WriteOnlyCollection.update` and 

1454 :meth:`_orm.WriteOnlyCollection.delete` are provided which generate SQL 

1455 constructs that may be used to load and modify rows in bulk. Used for 

1456 large collections that are never appropriate to load at once into 

1457 memory. 

1458 

1459 The ``write_only`` loader style is configured automatically when 

1460 the :class:`_orm.WriteOnlyMapped` annotation is provided on the 

1461 left hand side within a Declarative mapping. See the section 

1462 :ref:`write_only_relationship` for examples. 

1463 

1464 .. versionadded:: 2.0 

1465 

1466 .. seealso:: 

1467 

1468 :ref:`write_only_relationship` - in the :ref:`queryguide_toplevel` 

1469 

1470 * ``dynamic`` - the attribute will return a pre-configured 

1471 :class:`_query.Query` object for all read 

1472 operations, onto which further filtering operations can be 

1473 applied before iterating the results. 

1474 

1475 The ``dynamic`` loader style is configured automatically when 

1476 the :class:`_orm.DynamicMapped` annotation is provided on the 

1477 left hand side within a Declarative mapping. See the section 

1478 :ref:`dynamic_relationship` for examples. 

1479 

1480 .. legacy:: The "dynamic" lazy loader strategy is the legacy form of 

1481 what is now the "write_only" strategy described in the section 

1482 :ref:`write_only_relationship`. 

1483 

1484 .. seealso:: 

1485 

1486 :ref:`dynamic_relationship` - in the :ref:`queryguide_toplevel` 

1487 

1488 :ref:`write_only_relationship` - more generally useful approach 

1489 for large collections that should not fully load into memory 

1490 

1491 * ``noload`` - no loading should occur at any time. The related 

1492 collection will remain empty. 

1493 

1494 .. deprecated:: 2.1 The ``noload`` loader strategy is deprecated and 

1495 will be removed in a future release. This option produces incorrect 

1496 results by returning ``None`` for related items. 

1497 

1498 * True - a synonym for 'select' 

1499 

1500 * False - a synonym for 'joined' 

1501 

1502 * None - a synonym for 'noload' 

1503 

1504 .. seealso:: 

1505 

1506 :ref:`orm_queryguide_relationship_loaders` - Full documentation on 

1507 relationship loader configuration in the :ref:`queryguide_toplevel`. 

1508 

1509 

1510 :param load_on_pending=False: 

1511 Indicates loading behavior for transient or pending parent objects. 

1512 

1513 When set to ``True``, causes the lazy-loader to 

1514 issue a query for a parent object that is not persistent, meaning it 

1515 has never been flushed. This may take effect for a pending object 

1516 when autoflush is disabled, or for a transient object that has been 

1517 "attached" to a :class:`.Session` but is not part of its pending 

1518 collection. 

1519 

1520 The :paramref:`_orm.relationship.load_on_pending` 

1521 flag does not improve 

1522 behavior when the ORM is used normally - object references should be 

1523 constructed at the object level, not at the foreign key level, so 

1524 that they are present in an ordinary way before a flush proceeds. 

1525 This flag is not not intended for general use. 

1526 

1527 .. seealso:: 

1528 

1529 :meth:`.Session.enable_relationship_loading` - this method 

1530 establishes "load on pending" behavior for the whole object, and 

1531 also allows loading on objects that remain transient or 

1532 detached. 

1533 

1534 :param order_by: 

1535 Indicates the ordering that should be applied when loading these 

1536 items. :paramref:`_orm.relationship.order_by` 

1537 is expected to refer to 

1538 one of the :class:`_schema.Column` 

1539 objects to which the target class is 

1540 mapped, or the attribute itself bound to the target class which 

1541 refers to the column. 

1542 

1543 :paramref:`_orm.relationship.order_by` 

1544 may also be passed as a callable 

1545 function which is evaluated at mapper initialization time, and may 

1546 be passed as a Python-evaluable string when using Declarative. 

1547 

1548 .. warning:: When passed as a Python-evaluable string, the 

1549 argument is interpreted using Python's ``eval()`` function. 

1550 **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**. 

1551 See :ref:`declarative_relationship_eval` for details on 

1552 declarative evaluation of :func:`_orm.relationship` arguments. 

1553 

1554 :param passive_deletes=False: 

1555 Indicates loading behavior during delete operations. 

1556 

1557 A value of True indicates that unloaded child items should not 

1558 be loaded during a delete operation on the parent. Normally, 

1559 when a parent item is deleted, all child items are loaded so 

1560 that they can either be marked as deleted, or have their 

1561 foreign key to the parent set to NULL. Marking this flag as 

1562 True usually implies an ON DELETE <CASCADE|SET NULL> rule is in 

1563 place which will handle updating/deleting child rows on the 

1564 database side. 

1565 

1566 Additionally, setting the flag to the string value 'all' will 

1567 disable the "nulling out" of the child foreign keys, when the parent 

1568 object is deleted and there is no delete or delete-orphan cascade 

1569 enabled. This is typically used when a triggering or error raise 

1570 scenario is in place on the database side. Note that the foreign 

1571 key attributes on in-session child objects will not be changed after 

1572 a flush occurs so this is a very special use-case setting. 

1573 Additionally, the "nulling out" will still occur if the child 

1574 object is de-associated with the parent. 

1575 

1576 .. seealso:: 

1577 

1578 :ref:`passive_deletes` - Introductory documentation 

1579 and examples. 

1580 

1581 :param passive_updates=True: 

1582 Indicates the persistence behavior to take when a referenced 

1583 primary key value changes in place, indicating that the referencing 

1584 foreign key columns will also need their value changed. 

1585 

1586 When True, it is assumed that ``ON UPDATE CASCADE`` is configured on 

1587 the foreign key in the database, and that the database will 

1588 handle propagation of an UPDATE from a source column to 

1589 dependent rows. When False, the SQLAlchemy 

1590 :func:`_orm.relationship` 

1591 construct will attempt to emit its own UPDATE statements to 

1592 modify related targets. However note that SQLAlchemy **cannot** 

1593 emit an UPDATE for more than one level of cascade. Also, 

1594 setting this flag to False is not compatible in the case where 

1595 the database is in fact enforcing referential integrity, unless 

1596 those constraints are explicitly "deferred", if the target backend 

1597 supports it. 

1598 

1599 It is highly advised that an application which is employing 

1600 mutable primary keys keeps ``passive_updates`` set to True, 

1601 and instead uses the referential integrity features of the database 

1602 itself in order to handle the change efficiently and fully. 

1603 

1604 .. seealso:: 

1605 

1606 :ref:`passive_updates` - Introductory documentation and 

1607 examples. 

1608 

1609 :paramref:`.mapper.passive_updates` - a similar flag which 

1610 takes effect for joined-table inheritance mappings. 

1611 

1612 :param post_update: 

1613 This indicates that the relationship should be handled by a 

1614 second UPDATE statement after an INSERT or before a 

1615 DELETE. This flag is used to handle saving bi-directional 

1616 dependencies between two individual rows (i.e. each row 

1617 references the other), where it would otherwise be impossible to 

1618 INSERT or DELETE both rows fully since one row exists before the 

1619 other. Use this flag when a particular mapping arrangement will 

1620 incur two rows that are dependent on each other, such as a table 

1621 that has a one-to-many relationship to a set of child rows, and 

1622 also has a column that references a single child row within that 

1623 list (i.e. both tables contain a foreign key to each other). If 

1624 a flush operation returns an error that a "cyclical 

1625 dependency" was detected, this is a cue that you might want to 

1626 use :paramref:`_orm.relationship.post_update` to "break" the cycle. 

1627 

1628 .. seealso:: 

1629 

1630 :ref:`post_update` - Introductory documentation and examples. 

1631 

1632 :param primaryjoin: 

1633 A SQL expression that will be used as the primary 

1634 join of the child object against the parent object, or in a 

1635 many-to-many relationship the join of the parent object to the 

1636 association table. By default, this value is computed based on the 

1637 foreign key relationships of the parent and child tables (or 

1638 association table). 

1639 

1640 :paramref:`_orm.relationship.primaryjoin` may also be passed as a 

1641 callable function which is evaluated at mapper initialization time, 

1642 and may be passed as a Python-evaluable string when using 

1643 Declarative. 

1644 

1645 .. warning:: When passed as a Python-evaluable string, the 

1646 argument is interpreted using Python's ``eval()`` function. 

1647 **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**. 

1648 See :ref:`declarative_relationship_eval` for details on 

1649 declarative evaluation of :func:`_orm.relationship` arguments. 

1650 

1651 .. seealso:: 

1652 

1653 :ref:`relationship_primaryjoin` 

1654 

1655 :param remote_side: 

1656 Used for self-referential relationships, indicates the column or 

1657 list of columns that form the "remote side" of the relationship. 

1658 

1659 :paramref:`_orm.relationship.remote_side` may also be passed as a 

1660 callable function which is evaluated at mapper initialization time, 

1661 and may be passed as a Python-evaluable string when using 

1662 Declarative. 

1663 

1664 .. warning:: When passed as a Python-evaluable string, the 

1665 argument is interpreted using Python's ``eval()`` function. 

1666 **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**. 

1667 See :ref:`declarative_relationship_eval` for details on 

1668 declarative evaluation of :func:`_orm.relationship` arguments. 

1669 

1670 .. seealso:: 

1671 

1672 :ref:`self_referential` - in-depth explanation of how 

1673 :paramref:`_orm.relationship.remote_side` 

1674 is used to configure self-referential relationships. 

1675 

1676 :func:`.remote` - an annotation function that accomplishes the 

1677 same purpose as :paramref:`_orm.relationship.remote_side`, 

1678 typically 

1679 when a custom :paramref:`_orm.relationship.primaryjoin` condition 

1680 is used. 

1681 

1682 :param query_class: 

1683 A :class:`_query.Query` 

1684 subclass that will be used internally by the 

1685 ``AppenderQuery`` returned by a "dynamic" relationship, that 

1686 is, a relationship that specifies ``lazy="dynamic"`` or was 

1687 otherwise constructed using the :func:`_orm.dynamic_loader` 

1688 function. 

1689 

1690 .. seealso:: 

1691 

1692 :ref:`dynamic_relationship` - Introduction to "dynamic" 

1693 relationship loaders. 

1694 

1695 :param secondaryjoin: 

1696 A SQL expression that will be used as the join of 

1697 an association table to the child object. By default, this value is 

1698 computed based on the foreign key relationships of the association 

1699 and child tables. 

1700 

1701 :paramref:`_orm.relationship.secondaryjoin` may also be passed as a 

1702 callable function which is evaluated at mapper initialization time, 

1703 and may be passed as a Python-evaluable string when using 

1704 Declarative. 

1705 

1706 .. warning:: When passed as a Python-evaluable string, the 

1707 argument is interpreted using Python's ``eval()`` function. 

1708 **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**. 

1709 See :ref:`declarative_relationship_eval` for details on 

1710 declarative evaluation of :func:`_orm.relationship` arguments. 

1711 

1712 .. seealso:: 

1713 

1714 :ref:`relationship_primaryjoin` 

1715 

1716 :param single_parent: 

1717 When True, installs a validator which will prevent objects 

1718 from being associated with more than one parent at a time. 

1719 This is used for many-to-one or many-to-many relationships that 

1720 should be treated either as one-to-one or one-to-many. Its usage 

1721 is optional, except for :func:`_orm.relationship` constructs which 

1722 are many-to-one or many-to-many and also 

1723 specify the ``delete-orphan`` cascade option. The 

1724 :func:`_orm.relationship` construct itself will raise an error 

1725 instructing when this option is required. 

1726 

1727 .. seealso:: 

1728 

1729 :ref:`unitofwork_cascades` - includes detail on when the 

1730 :paramref:`_orm.relationship.single_parent` 

1731 flag may be appropriate. 

1732 

1733 :param uselist: 

1734 A boolean that indicates if this property should be loaded as a 

1735 list or a scalar. In most cases, this value is determined 

1736 automatically by :func:`_orm.relationship` at mapper configuration 

1737 time. When using explicit :class:`_orm.Mapped` annotations, 

1738 :paramref:`_orm.relationship.uselist` may be derived from the 

1739 whether or not the annotation within :class:`_orm.Mapped` contains 

1740 a collection class. 

1741 Otherwise, :paramref:`_orm.relationship.uselist` may be derived from 

1742 the type and direction 

1743 of the relationship - one to many forms a list, many to one 

1744 forms a scalar, many to many is a list. If a scalar is desired 

1745 where normally a list would be present, such as a bi-directional 

1746 one-to-one relationship, use an appropriate :class:`_orm.Mapped` 

1747 annotation or set :paramref:`_orm.relationship.uselist` to False. 

1748 

1749 The :paramref:`_orm.relationship.uselist` 

1750 flag is also available on an 

1751 existing :func:`_orm.relationship` 

1752 construct as a read-only attribute, 

1753 which can be used to determine if this :func:`_orm.relationship` 

1754 deals 

1755 with collections or scalar attributes:: 

1756 

1757 >>> User.addresses.property.uselist 

1758 True 

1759 

1760 .. seealso:: 

1761 

1762 :ref:`relationships_one_to_one` - Introduction to the "one to 

1763 one" relationship pattern, which is typically when an alternate 

1764 setting for :paramref:`_orm.relationship.uselist` is involved. 

1765 

1766 :param viewonly=False: 

1767 When set to ``True``, the relationship is used only for loading 

1768 objects, and not for any persistence operation. A 

1769 :func:`_orm.relationship` which specifies 

1770 :paramref:`_orm.relationship.viewonly` can work 

1771 with a wider range of SQL operations within the 

1772 :paramref:`_orm.relationship.primaryjoin` condition, including 

1773 operations that feature the use of a variety of comparison operators 

1774 as well as SQL functions such as :func:`_expression.cast`. The 

1775 :paramref:`_orm.relationship.viewonly` 

1776 flag is also of general use when defining any kind of 

1777 :func:`_orm.relationship` that doesn't represent 

1778 the full set of related objects, to prevent modifications of the 

1779 collection from resulting in persistence operations. 

1780 

1781 .. seealso:: 

1782 

1783 :ref:`relationship_viewonly_notes` - more details on best practices 

1784 when using :paramref:`_orm.relationship.viewonly`. 

1785 

1786 :param sync_backref: 

1787 A boolean that enables the events used to synchronize the in-Python 

1788 attributes when this relationship is target of either 

1789 :paramref:`_orm.relationship.backref` or 

1790 :paramref:`_orm.relationship.back_populates`. 

1791 

1792 Defaults to ``None``, which indicates that an automatic value should 

1793 be selected based on the value of the 

1794 :paramref:`_orm.relationship.viewonly` flag. When left at its 

1795 default, changes in state will be back-populated only if neither 

1796 sides of a relationship is viewonly. 

1797 

1798 .. versionchanged:: 1.4 - A relationship that specifies 

1799 :paramref:`_orm.relationship.viewonly` automatically implies 

1800 that :paramref:`_orm.relationship.sync_backref` is ``False``. 

1801 

1802 .. seealso:: 

1803 

1804 :paramref:`_orm.relationship.viewonly` 

1805 

1806 :param omit_join: 

1807 Allows manual control over the "selectin" automatic join 

1808 optimization. Set to ``False`` to disable the "omit join" feature 

1809 added in SQLAlchemy 1.3; or leave as ``None`` to leave automatic 

1810 optimization in place. 

1811 

1812 .. note:: This flag may only be set to ``False``. It is not 

1813 necessary to set it to ``True`` as the "omit_join" optimization is 

1814 automatically detected; if it is not detected, then the 

1815 optimization is not supported. 

1816 

1817 :param default: Specific to :ref:`orm_declarative_native_dataclasses`, 

1818 specifies an immutable scalar default value for the relationship that 

1819 will behave as though it is the default value for the parameter in the 

1820 ``__init__()`` method. This is only supported for a ``uselist=False`` 

1821 relationship, that is many-to-one or one-to-one, and only supports the 

1822 scalar value ``None``, since no other immutable value is valid for such a 

1823 relationship. 

1824 

1825 .. versionchanged:: 2.1 the :paramref:`_orm.relationship.default` 

1826 parameter only supports a value of ``None``. 

1827 

1828 :param init: Specific to :ref:`orm_declarative_native_dataclasses`, 

1829 specifies if the mapped attribute should be part of the ``__init__()`` 

1830 method as generated by the dataclass process. 

1831 :param repr: Specific to :ref:`orm_declarative_native_dataclasses`, 

1832 specifies if the mapped attribute should be part of the ``__repr__()`` 

1833 method as generated by the dataclass process. 

1834 :param default_factory: Specific to 

1835 :ref:`orm_declarative_native_dataclasses`, 

1836 specifies a default-value generation function that will take place 

1837 as part of the ``__init__()`` 

1838 method as generated by the dataclass process. 

1839 :param compare: Specific to 

1840 :ref:`orm_declarative_native_dataclasses`, indicates if this field 

1841 should be included in comparison operations when generating the 

1842 ``__eq__()`` and ``__ne__()`` methods for the mapped class. 

1843 

1844 .. versionadded:: 2.0.0b4 

1845 

1846 :param kw_only: Specific to 

1847 :ref:`orm_declarative_native_dataclasses`, indicates if this field 

1848 should be marked as keyword-only when generating the ``__init__()``. 

1849 

1850 :param hash: Specific to 

1851 :ref:`orm_declarative_native_dataclasses`, controls if this field 

1852 is included when generating the ``__hash__()`` method for the mapped 

1853 class. 

1854 

1855 .. versionadded:: 2.0.36 

1856 """ 

1857 

1858 return _RelationshipDeclared( 

1859 argument, 

1860 secondary=secondary, 

1861 uselist=uselist, 

1862 collection_class=collection_class, 

1863 primaryjoin=primaryjoin, 

1864 secondaryjoin=secondaryjoin, 

1865 back_populates=back_populates, 

1866 order_by=order_by, 

1867 backref=backref, 

1868 overlaps=overlaps, 

1869 post_update=post_update, 

1870 cascade=cascade, 

1871 viewonly=viewonly, 

1872 attribute_options=_AttributeOptions( 

1873 init, repr, default, default_factory, compare, kw_only, hash 

1874 ), 

1875 lazy=lazy, 

1876 passive_deletes=passive_deletes, 

1877 passive_updates=passive_updates, 

1878 active_history=active_history, 

1879 enable_typechecks=enable_typechecks, 

1880 foreign_keys=foreign_keys, 

1881 remote_side=remote_side, 

1882 join_depth=join_depth, 

1883 comparator_factory=comparator_factory, 

1884 single_parent=single_parent, 

1885 innerjoin=innerjoin, 

1886 distinct_target_key=distinct_target_key, 

1887 load_on_pending=load_on_pending, 

1888 query_class=query_class, 

1889 info=info, 

1890 omit_join=omit_join, 

1891 sync_backref=sync_backref, 

1892 **kw, 

1893 ) 

1894 

1895 

1896def synonym( 

1897 name: str, 

1898 *, 

1899 map_column: Optional[bool] = None, 

1900 descriptor: Optional[Any] = None, 

1901 comparator_factory: Optional[Type[PropComparator[_T]]] = None, 

1902 init: Union[_NoArg, bool] = _NoArg.NO_ARG, 

1903 repr: Union[_NoArg, bool] = _NoArg.NO_ARG, # noqa: A002 

1904 default: Union[_NoArg, _T] = _NoArg.NO_ARG, 

1905 default_factory: Union[_NoArg, Callable[[], _T]] = _NoArg.NO_ARG, 

1906 compare: Union[_NoArg, bool] = _NoArg.NO_ARG, 

1907 kw_only: Union[_NoArg, bool] = _NoArg.NO_ARG, 

1908 hash: Union[_NoArg, bool, None] = _NoArg.NO_ARG, # noqa: A002 

1909 info: Optional[_InfoType] = None, 

1910 doc: Optional[str] = None, 

1911) -> Synonym[Any]: 

1912 """Denote an attribute name as a synonym to a mapped property, 

1913 in that the attribute will mirror the value and expression behavior 

1914 of another attribute. 

1915 

1916 e.g.:: 

1917 

1918 class MyClass(Base): 

1919 __tablename__ = "my_table" 

1920 

1921 id = Column(Integer, primary_key=True) 

1922 job_status = Column(String(50)) 

1923 

1924 status = synonym("job_status") 

1925 

1926 :param name: the name of the existing mapped property. This 

1927 can refer to the string name ORM-mapped attribute 

1928 configured on the class, including column-bound attributes 

1929 and relationships. 

1930 

1931 :param descriptor: a Python :term:`descriptor` that will be used 

1932 as a getter (and potentially a setter) when this attribute is 

1933 accessed at the instance level. 

1934 

1935 :param map_column: **For classical mappings and mappings against 

1936 an existing Table object only**. if ``True``, the :func:`.synonym` 

1937 construct will locate the :class:`_schema.Column` 

1938 object upon the mapped 

1939 table that would normally be associated with the attribute name of 

1940 this synonym, and produce a new :class:`.ColumnProperty` that instead 

1941 maps this :class:`_schema.Column` 

1942 to the alternate name given as the "name" 

1943 argument of the synonym; in this way, the usual step of redefining 

1944 the mapping of the :class:`_schema.Column` 

1945 to be under a different name is 

1946 unnecessary. This is usually intended to be used when a 

1947 :class:`_schema.Column` 

1948 is to be replaced with an attribute that also uses a 

1949 descriptor, that is, in conjunction with the 

1950 :paramref:`.synonym.descriptor` parameter:: 

1951 

1952 my_table = Table( 

1953 "my_table", 

1954 metadata, 

1955 Column("id", Integer, primary_key=True), 

1956 Column("job_status", String(50)), 

1957 ) 

1958 

1959 

1960 class MyClass: 

1961 @property 

1962 def _job_status_descriptor(self): 

1963 return "Status: %s" % self._job_status 

1964 

1965 

1966 mapper( 

1967 MyClass, 

1968 my_table, 

1969 properties={ 

1970 "job_status": synonym( 

1971 "_job_status", 

1972 map_column=True, 

1973 descriptor=MyClass._job_status_descriptor, 

1974 ) 

1975 }, 

1976 ) 

1977 

1978 Above, the attribute named ``_job_status`` is automatically 

1979 mapped to the ``job_status`` column:: 

1980 

1981 >>> j1 = MyClass() 

1982 >>> j1._job_status = "employed" 

1983 >>> j1.job_status 

1984 Status: employed 

1985 

1986 When using Declarative, in order to provide a descriptor in 

1987 conjunction with a synonym, use the 

1988 :func:`sqlalchemy.ext.declarative.synonym_for` helper. However, 

1989 note that the :ref:`hybrid properties <mapper_hybrids>` feature 

1990 should usually be preferred, particularly when redefining attribute 

1991 behavior. 

1992 

1993 :param info: Optional data dictionary which will be populated into the 

1994 :attr:`.InspectionAttr.info` attribute of this object. 

1995 

1996 :param comparator_factory: A subclass of :class:`.PropComparator` 

1997 that will provide custom comparison behavior at the SQL expression 

1998 level. 

1999 

2000 .. note:: 

2001 

2002 For the use case of providing an attribute which redefines both 

2003 Python-level and SQL-expression level behavior of an attribute, 

2004 please refer to the Hybrid attribute introduced at 

2005 :ref:`mapper_hybrids` for a more effective technique. 

2006 

2007 .. seealso:: 

2008 

2009 :ref:`synonyms` - Overview of synonyms 

2010 

2011 :func:`.synonym_for` - a helper oriented towards Declarative 

2012 

2013 :ref:`mapper_hybrids` - The Hybrid Attribute extension provides an 

2014 updated approach to augmenting attribute behavior more flexibly 

2015 than can be achieved with synonyms. 

2016 

2017 """ 

2018 return Synonym( 

2019 name, 

2020 map_column=map_column, 

2021 descriptor=descriptor, 

2022 comparator_factory=comparator_factory, 

2023 attribute_options=_AttributeOptions( 

2024 init, repr, default, default_factory, compare, kw_only, hash 

2025 ), 

2026 doc=doc, 

2027 info=info, 

2028 ) 

2029 

2030 

2031def create_session( 

2032 bind: Optional[_SessionBind] = None, **kwargs: Any 

2033) -> Session: 

2034 r"""Create a new :class:`.Session` 

2035 with no automation enabled by default. 

2036 

2037 This function is used primarily for testing. The usual 

2038 route to :class:`.Session` creation is via its constructor 

2039 or the :func:`.sessionmaker` function. 

2040 

2041 :param bind: optional, a single Connectable to use for all 

2042 database access in the created 

2043 :class:`~sqlalchemy.orm.session.Session`. 

2044 

2045 :param \*\*kwargs: optional, passed through to the 

2046 :class:`.Session` constructor. 

2047 

2048 :returns: an :class:`~sqlalchemy.orm.session.Session` instance 

2049 

2050 The defaults of create_session() are the opposite of that of 

2051 :func:`sessionmaker`; ``autoflush`` and ``expire_on_commit`` are 

2052 False. 

2053 

2054 Usage:: 

2055 

2056 >>> from sqlalchemy.orm import create_session 

2057 >>> session = create_session() 

2058 

2059 It is recommended to use :func:`sessionmaker` instead of 

2060 create_session(). 

2061 

2062 """ 

2063 

2064 kwargs.setdefault("autoflush", False) 

2065 kwargs.setdefault("expire_on_commit", False) 

2066 return Session(bind=bind, **kwargs) 

2067 

2068 

2069def _mapper_fn(*arg: Any, **kw: Any) -> NoReturn: 

2070 """Placeholder for the now-removed ``mapper()`` function. 

2071 

2072 Classical mappings should be performed using the 

2073 :meth:`_orm.registry.map_imperatively` method. 

2074 

2075 This symbol remains in SQLAlchemy 2.0 to suit the deprecated use case 

2076 of using the ``mapper()`` function as a target for ORM event listeners, 

2077 which failed to be marked as deprecated in the 1.4 series. 

2078 

2079 Global ORM mapper listeners should instead use the :class:`_orm.Mapper` 

2080 class as the target. 

2081 

2082 .. versionchanged:: 2.0 The ``mapper()`` function was removed; the 

2083 symbol remains temporarily as a placeholder for the event listening 

2084 use case. 

2085 

2086 """ 

2087 raise InvalidRequestError( 

2088 "The 'sqlalchemy.orm.mapper()' function is removed as of " 

2089 "SQLAlchemy 2.0. Use the " 

2090 "'sqlalchemy.orm.registry.map_imperatively()` " 

2091 "method of the ``sqlalchemy.orm.registry`` class to perform " 

2092 "classical mapping." 

2093 ) 

2094 

2095 

2096def dynamic_loader( 

2097 argument: Optional[_RelationshipArgumentType[Any]] = None, **kw: Any 

2098) -> RelationshipProperty[Any]: 

2099 """Construct a dynamically-loading mapper property. 

2100 

2101 This is essentially the same as 

2102 using the ``lazy='dynamic'`` argument with :func:`relationship`:: 

2103 

2104 dynamic_loader(SomeClass) 

2105 

2106 # is the same as 

2107 

2108 relationship(SomeClass, lazy="dynamic") 

2109 

2110 See the section :ref:`dynamic_relationship` for more details 

2111 on dynamic loading. 

2112 

2113 """ 

2114 kw["lazy"] = "dynamic" 

2115 return relationship(argument, **kw) 

2116 

2117 

2118def backref(name: str, **kwargs: Any) -> ORMBackrefArgument: 

2119 """When using the :paramref:`_orm.relationship.backref` parameter, 

2120 provides specific parameters to be used when the new 

2121 :func:`_orm.relationship` is generated. 

2122 

2123 E.g.:: 

2124 

2125 "items": relationship(SomeItem, backref=backref("parent", lazy="subquery")) 

2126 

2127 The :paramref:`_orm.relationship.backref` parameter is generally 

2128 considered to be legacy; for modern applications, using 

2129 explicit :func:`_orm.relationship` constructs linked together using 

2130 the :paramref:`_orm.relationship.back_populates` parameter should be 

2131 preferred. 

2132 

2133 .. seealso:: 

2134 

2135 :ref:`relationships_backref` - background on backrefs 

2136 

2137 """ # noqa: E501 

2138 

2139 return (name, kwargs) 

2140 

2141 

2142def deferred( 

2143 column: _ORMColumnExprArgument[_T], 

2144 *additional_columns: _ORMColumnExprArgument[Any], 

2145 group: Optional[str] = None, 

2146 raiseload: bool = False, 

2147 comparator_factory: Optional[Type[PropComparator[_T]]] = None, 

2148 init: Union[_NoArg, bool] = _NoArg.NO_ARG, 

2149 repr: Union[_NoArg, bool] = _NoArg.NO_ARG, # noqa: A002 

2150 default: Optional[Any] = _NoArg.NO_ARG, 

2151 default_factory: Union[_NoArg, Callable[[], _T]] = _NoArg.NO_ARG, 

2152 compare: Union[_NoArg, bool] = _NoArg.NO_ARG, 

2153 kw_only: Union[_NoArg, bool] = _NoArg.NO_ARG, 

2154 hash: Union[_NoArg, bool, None] = _NoArg.NO_ARG, # noqa: A002 

2155 active_history: bool = False, 

2156 expire_on_flush: bool = True, 

2157 info: Optional[_InfoType] = None, 

2158 doc: Optional[str] = None, 

2159) -> MappedSQLExpression[_T]: 

2160 r"""Indicate a column-based mapped attribute that by default will 

2161 not load unless accessed. 

2162 

2163 When using :func:`_orm.mapped_column`, the same functionality as 

2164 that of :func:`_orm.deferred` construct is provided by using the 

2165 :paramref:`_orm.mapped_column.deferred` parameter. 

2166 

2167 :param \*columns: columns to be mapped. This is typically a single 

2168 :class:`_schema.Column` object, 

2169 however a collection is supported in order 

2170 to support multiple columns mapped under the same attribute. 

2171 

2172 :param raiseload: boolean, if True, indicates an exception should be raised 

2173 if the load operation is to take place. 

2174 

2175 .. versionadded:: 1.4 

2176 

2177 

2178 Additional arguments are the same as that of :func:`_orm.column_property`. 

2179 

2180 .. seealso:: 

2181 

2182 :ref:`orm_queryguide_deferred_imperative` 

2183 

2184 """ 

2185 return MappedSQLExpression( 

2186 column, 

2187 *additional_columns, 

2188 attribute_options=_AttributeOptions( 

2189 init, repr, default, default_factory, compare, kw_only, hash 

2190 ), 

2191 group=group, 

2192 deferred=True, 

2193 raiseload=raiseload, 

2194 comparator_factory=comparator_factory, 

2195 active_history=active_history, 

2196 expire_on_flush=expire_on_flush, 

2197 info=info, 

2198 doc=doc, 

2199 ) 

2200 

2201 

2202def query_expression( 

2203 default_expr: _ORMColumnExprArgument[_T] = sql.null(), 

2204 *, 

2205 repr: Union[_NoArg, bool] = _NoArg.NO_ARG, # noqa: A002 

2206 compare: Union[_NoArg, bool] = _NoArg.NO_ARG, # noqa: A002 

2207 expire_on_flush: bool = True, 

2208 info: Optional[_InfoType] = None, 

2209 doc: Optional[str] = None, 

2210) -> MappedSQLExpression[_T]: 

2211 """Indicate an attribute that populates from a query-time SQL expression. 

2212 

2213 :param default_expr: Optional SQL expression object that will be used in 

2214 all cases if not assigned later with :func:`_orm.with_expression`. 

2215 

2216 .. seealso:: 

2217 

2218 :ref:`orm_queryguide_with_expression` - background and usage examples 

2219 

2220 """ 

2221 prop = MappedSQLExpression( 

2222 default_expr, 

2223 attribute_options=_AttributeOptions( 

2224 False, 

2225 repr, 

2226 _NoArg.NO_ARG, 

2227 _NoArg.NO_ARG, 

2228 compare, 

2229 _NoArg.NO_ARG, 

2230 _NoArg.NO_ARG, 

2231 ), 

2232 expire_on_flush=expire_on_flush, 

2233 info=info, 

2234 doc=doc, 

2235 _assume_readonly_dc_attributes=True, 

2236 ) 

2237 

2238 prop.strategy_key = (("query_expression", True),) 

2239 return prop 

2240 

2241 

2242def clear_mappers() -> None: 

2243 """Remove all mappers from all classes. 

2244 

2245 .. versionchanged:: 1.4 This function now locates all 

2246 :class:`_orm.registry` objects and calls upon the 

2247 :meth:`_orm.registry.dispose` method of each. 

2248 

2249 This function removes all instrumentation from classes and disposes 

2250 of their associated mappers. Once called, the classes are unmapped 

2251 and can be later re-mapped with new mappers. 

2252 

2253 :func:`.clear_mappers` is *not* for normal use, as there is literally no 

2254 valid usage for it outside of very specific testing scenarios. Normally, 

2255 mappers are permanent structural components of user-defined classes, and 

2256 are never discarded independently of their class. If a mapped class 

2257 itself is garbage collected, its mapper is automatically disposed of as 

2258 well. As such, :func:`.clear_mappers` is only for usage in test suites 

2259 that re-use the same classes with different mappings, which is itself an 

2260 extremely rare use case - the only such use case is in fact SQLAlchemy's 

2261 own test suite, and possibly the test suites of other ORM extension 

2262 libraries which intend to test various combinations of mapper construction 

2263 upon a fixed set of classes. 

2264 

2265 """ 

2266 

2267 mapperlib._dispose_registries(mapperlib._all_registries(), False) 

2268 

2269 

2270# I would really like a way to get the Type[] here that shows up 

2271# in a different way in typing tools, however there is no current method 

2272# that is accepted by mypy (subclass of Type[_O] works in pylance, rejected 

2273# by mypy). 

2274AliasedType = Annotated[Type[_O], "aliased"] 

2275 

2276 

2277@overload 

2278def aliased( 

2279 element: Type[_O], 

2280 alias: Optional[FromClause] = None, 

2281 name: Optional[str] = None, 

2282 flat: bool = False, 

2283 adapt_on_names: bool = False, 

2284) -> AliasedType[_O]: ... 

2285 

2286 

2287@overload 

2288def aliased( 

2289 element: Union[AliasedClass[_O], Mapper[_O], AliasedInsp[_O]], 

2290 alias: Optional[FromClause] = None, 

2291 name: Optional[str] = None, 

2292 flat: bool = False, 

2293 adapt_on_names: bool = False, 

2294) -> AliasedClass[_O]: ... 

2295 

2296 

2297@overload 

2298def aliased( 

2299 element: FromClause, 

2300 alias: None = None, 

2301 name: Optional[str] = None, 

2302 flat: bool = False, 

2303 adapt_on_names: bool = False, 

2304) -> FromClause: ... 

2305 

2306 

2307def aliased( 

2308 element: Union[_EntityType[_O], FromClause], 

2309 alias: Optional[FromClause] = None, 

2310 name: Optional[str] = None, 

2311 flat: bool = False, 

2312 adapt_on_names: bool = False, 

2313) -> Union[AliasedClass[_O], FromClause, AliasedType[_O]]: 

2314 """Produce an alias of the given element, usually an :class:`.AliasedClass` 

2315 instance. 

2316 

2317 E.g.:: 

2318 

2319 my_alias = aliased(MyClass) 

2320 

2321 stmt = select(MyClass, my_alias).filter(MyClass.id > my_alias.id) 

2322 result = session.execute(stmt) 

2323 

2324 The :func:`.aliased` function is used to create an ad-hoc mapping of a 

2325 mapped class to a new selectable. By default, a selectable is generated 

2326 from the normally mapped selectable (typically a :class:`_schema.Table` 

2327 ) using the 

2328 :meth:`_expression.FromClause.alias` method. However, :func:`.aliased` 

2329 can also be 

2330 used to link the class to a new :func:`_expression.select` statement. 

2331 Also, the :func:`.with_polymorphic` function is a variant of 

2332 :func:`.aliased` that is intended to specify a so-called "polymorphic 

2333 selectable", that corresponds to the union of several joined-inheritance 

2334 subclasses at once. 

2335 

2336 For convenience, the :func:`.aliased` function also accepts plain 

2337 :class:`_expression.FromClause` constructs, such as a 

2338 :class:`_schema.Table` or 

2339 :func:`_expression.select` construct. In those cases, the 

2340 :meth:`_expression.FromClause.alias` 

2341 method is called on the object and the new 

2342 :class:`_expression.Alias` object returned. The returned 

2343 :class:`_expression.Alias` is not 

2344 ORM-mapped in this case. 

2345 

2346 .. seealso:: 

2347 

2348 :ref:`tutorial_orm_entity_aliases` - in the :ref:`unified_tutorial` 

2349 

2350 :ref:`orm_queryguide_orm_aliases` - in the :ref:`queryguide_toplevel` 

2351 

2352 :param element: element to be aliased. Is normally a mapped class, 

2353 but for convenience can also be a :class:`_expression.FromClause` 

2354 element. 

2355 

2356 :param alias: Optional selectable unit to map the element to. This is 

2357 usually used to link the object to a subquery, and should be an aliased 

2358 select construct as one would produce from the 

2359 :meth:`_query.Query.subquery` method or 

2360 the :meth:`_expression.Select.subquery` or 

2361 :meth:`_expression.Select.alias` methods of the :func:`_expression.select` 

2362 construct. 

2363 

2364 :param name: optional string name to use for the alias, if not specified 

2365 by the ``alias`` parameter. The name, among other things, forms the 

2366 attribute name that will be accessible via tuples returned by a 

2367 :class:`_query.Query` object. Not supported when creating aliases 

2368 of :class:`_sql.Join` objects. 

2369 

2370 :param flat: Boolean, will be passed through to the 

2371 :meth:`_expression.FromClause.alias` call so that aliases of 

2372 :class:`_expression.Join` objects will alias the individual tables 

2373 inside the join, rather than creating a subquery. This is generally 

2374 supported by all modern databases with regards to right-nested joins 

2375 and generally produces more efficient queries. 

2376 

2377 When :paramref:`_orm.aliased.flat` is combined with 

2378 :paramref:`_orm.aliased.name`, the resulting joins will alias individual 

2379 tables using a naming scheme similar to ``<prefix>_<tablename>``. This 

2380 naming scheme is for visibility / debugging purposes only and the 

2381 specific scheme is subject to change without notice. 

2382 

2383 .. versionadded:: 2.0.32 added support for combining 

2384 :paramref:`_orm.aliased.name` with :paramref:`_orm.aliased.flat`. 

2385 Previously, this would raise ``NotImplementedError``. 

2386 

2387 :param adapt_on_names: if True, more liberal "matching" will be used when 

2388 mapping the mapped columns of the ORM entity to those of the 

2389 given selectable - a name-based match will be performed if the 

2390 given selectable doesn't otherwise have a column that corresponds 

2391 to one on the entity. The use case for this is when associating 

2392 an entity with some derived selectable such as one that uses 

2393 aggregate functions:: 

2394 

2395 class UnitPrice(Base): 

2396 __tablename__ = "unit_price" 

2397 ... 

2398 unit_id = Column(Integer) 

2399 price = Column(Numeric) 

2400 

2401 

2402 aggregated_unit_price = ( 

2403 Session.query(func.sum(UnitPrice.price).label("price")) 

2404 .group_by(UnitPrice.unit_id) 

2405 .subquery() 

2406 ) 

2407 

2408 aggregated_unit_price = aliased( 

2409 UnitPrice, alias=aggregated_unit_price, adapt_on_names=True 

2410 ) 

2411 

2412 Above, functions on ``aggregated_unit_price`` which refer to 

2413 ``.price`` will return the 

2414 ``func.sum(UnitPrice.price).label('price')`` column, as it is 

2415 matched on the name "price". Ordinarily, the "price" function 

2416 wouldn't have any "column correspondence" to the actual 

2417 ``UnitPrice.price`` column as it is not a proxy of the original. 

2418 

2419 """ 

2420 return AliasedInsp._alias_factory( 

2421 element, 

2422 alias=alias, 

2423 name=name, 

2424 flat=flat, 

2425 adapt_on_names=adapt_on_names, 

2426 ) 

2427 

2428 

2429def with_polymorphic( 

2430 base: Union[Type[_O], Mapper[_O]], 

2431 classes: Union[Literal["*"], Iterable[Type[Any]]], 

2432 selectable: Union[Literal[False, None], FromClause] = False, 

2433 flat: bool = False, 

2434 polymorphic_on: Optional[ColumnElement[Any]] = None, 

2435 aliased: bool = False, 

2436 innerjoin: bool = False, 

2437 adapt_on_names: bool = False, 

2438 name: Optional[str] = None, 

2439 _use_mapper_path: bool = False, 

2440) -> AliasedClass[_O]: 

2441 """Produce an :class:`.AliasedClass` construct which specifies 

2442 columns for descendant mappers of the given base. 

2443 

2444 Using this method will ensure that each descendant mapper's 

2445 tables are included in the FROM clause, and will allow filter() 

2446 criterion to be used against those tables. The resulting 

2447 instances will also have those columns already loaded so that 

2448 no "post fetch" of those columns will be required. 

2449 

2450 .. seealso:: 

2451 

2452 :ref:`with_polymorphic` - full discussion of 

2453 :func:`_orm.with_polymorphic`. 

2454 

2455 :param base: Base class to be aliased. 

2456 

2457 :param classes: a single class or mapper, or list of 

2458 class/mappers, which inherit from the base class. 

2459 Alternatively, it may also be the string ``'*'``, in which case 

2460 all descending mapped classes will be added to the FROM clause. 

2461 

2462 :param aliased: when True, the selectable will be aliased. For a 

2463 JOIN, this means the JOIN will be SELECTed from inside of a subquery 

2464 unless the :paramref:`_orm.with_polymorphic.flat` flag is set to 

2465 True, which is recommended for simpler use cases. 

2466 

2467 :param flat: Boolean, will be passed through to the 

2468 :meth:`_expression.FromClause.alias` call so that aliases of 

2469 :class:`_expression.Join` objects will alias the individual tables 

2470 inside the join, rather than creating a subquery. This is generally 

2471 supported by all modern databases with regards to right-nested joins 

2472 and generally produces more efficient queries. Setting this flag is 

2473 recommended as long as the resulting SQL is functional. 

2474 

2475 :param selectable: a table or subquery that will 

2476 be used in place of the generated FROM clause. This argument is 

2477 required if any of the desired classes use concrete table 

2478 inheritance, since SQLAlchemy currently cannot generate UNIONs 

2479 among tables automatically. If used, the ``selectable`` argument 

2480 must represent the full set of tables and columns mapped by every 

2481 mapped class. Otherwise, the unaccounted mapped columns will 

2482 result in their table being appended directly to the FROM clause 

2483 which will usually lead to incorrect results. 

2484 

2485 When left at its default value of ``False``, the polymorphic 

2486 selectable assigned to the base mapper is used for selecting rows. 

2487 However, it may also be passed as ``None``, which will bypass the 

2488 configured polymorphic selectable and instead construct an ad-hoc 

2489 selectable for the target classes given; for joined table inheritance 

2490 this will be a join that includes all target mappers and their 

2491 subclasses. 

2492 

2493 :param polymorphic_on: a column to be used as the "discriminator" 

2494 column for the given selectable. If not given, the polymorphic_on 

2495 attribute of the base classes' mapper will be used, if any. This 

2496 is useful for mappings that don't have polymorphic loading 

2497 behavior by default. 

2498 

2499 :param innerjoin: if True, an INNER JOIN will be used. This should 

2500 only be specified if querying for one specific subtype only 

2501 

2502 :param adapt_on_names: Passes through the 

2503 :paramref:`_orm.aliased.adapt_on_names` 

2504 parameter to the aliased object. This may be useful in situations where 

2505 the given selectable is not directly related to the existing mapped 

2506 selectable. 

2507 

2508 .. versionadded:: 1.4.33 

2509 

2510 :param name: Name given to the generated :class:`.AliasedClass`. 

2511 

2512 .. versionadded:: 2.0.31 

2513 

2514 """ 

2515 return AliasedInsp._with_polymorphic_factory( 

2516 base, 

2517 classes, 

2518 selectable=selectable, 

2519 flat=flat, 

2520 polymorphic_on=polymorphic_on, 

2521 adapt_on_names=adapt_on_names, 

2522 aliased=aliased, 

2523 innerjoin=innerjoin, 

2524 name=name, 

2525 _use_mapper_path=_use_mapper_path, 

2526 ) 

2527 

2528 

2529def join( 

2530 left: _FromClauseArgument, 

2531 right: _FromClauseArgument, 

2532 onclause: Optional[_OnClauseArgument] = None, 

2533 isouter: bool = False, 

2534 full: bool = False, 

2535) -> _ORMJoin: 

2536 r"""Produce an inner join between left and right clauses. 

2537 

2538 :func:`_orm.join` is an extension to the core join interface 

2539 provided by :func:`_expression.join()`, where the 

2540 left and right selectable may be not only core selectable 

2541 objects such as :class:`_schema.Table`, but also mapped classes or 

2542 :class:`.AliasedClass` instances. The "on" clause can 

2543 be a SQL expression or an ORM mapped attribute 

2544 referencing a configured :func:`_orm.relationship`. 

2545 

2546 :func:`_orm.join` is not commonly needed in modern usage, 

2547 as its functionality is encapsulated within that of the 

2548 :meth:`_sql.Select.join` and :meth:`_query.Query.join` 

2549 methods. which feature a 

2550 significant amount of automation beyond :func:`_orm.join` 

2551 by itself. Explicit use of :func:`_orm.join` 

2552 with ORM-enabled SELECT statements involves use of the 

2553 :meth:`_sql.Select.select_from` method, as in:: 

2554 

2555 from sqlalchemy.orm import join 

2556 

2557 stmt = ( 

2558 select(User) 

2559 .select_from(join(User, Address, User.addresses)) 

2560 .filter(Address.email_address == "foo@bar.com") 

2561 ) 

2562 

2563 In modern SQLAlchemy the above join can be written more 

2564 succinctly as:: 

2565 

2566 stmt = ( 

2567 select(User) 

2568 .join(User.addresses) 

2569 .filter(Address.email_address == "foo@bar.com") 

2570 ) 

2571 

2572 .. warning:: using :func:`_orm.join` directly may not work properly 

2573 with modern ORM options such as :func:`_orm.with_loader_criteria`. 

2574 It is strongly recommended to use the idiomatic join patterns 

2575 provided by methods such as :meth:`.Select.join` and 

2576 :meth:`.Select.join_from` when creating ORM joins. 

2577 

2578 .. seealso:: 

2579 

2580 :ref:`orm_queryguide_joins` - in the :ref:`queryguide_toplevel` for 

2581 background on idiomatic ORM join patterns 

2582 

2583 """ 

2584 return _ORMJoin(left, right, onclause, isouter, full) 

2585 

2586 

2587def outerjoin( 

2588 left: _FromClauseArgument, 

2589 right: _FromClauseArgument, 

2590 onclause: Optional[_OnClauseArgument] = None, 

2591 full: bool = False, 

2592) -> _ORMJoin: 

2593 """Produce a left outer join between left and right clauses. 

2594 

2595 This is the "outer join" version of the :func:`_orm.join` function, 

2596 featuring the same behavior except that an OUTER JOIN is generated. 

2597 See that function's documentation for other usage details. 

2598 

2599 """ 

2600 return _ORMJoin(left, right, onclause, True, full)