Create filtering criterion that relates this query's primary entity to the given related instance, using established :func:`_orm.relationship()` configuration. E.g.:: stmt = select(Address).where(with_parent(some_user, User.addresses)) The SQL rendered is the same as t
(
instance: object,
prop: attributes.QueryableAttribute[Any],
from_entity: Optional[_EntityType[Any]] = None,
)
| 2000 | |
| 2001 | |
| 2002 | def with_parent( |
| 2003 | instance: object, |
| 2004 | prop: attributes.QueryableAttribute[Any], |
| 2005 | from_entity: Optional[_EntityType[Any]] = None, |
| 2006 | ) -> ColumnElement[bool]: |
| 2007 | """Create filtering criterion that relates this query's primary entity |
| 2008 | to the given related instance, using established |
| 2009 | :func:`_orm.relationship()` |
| 2010 | configuration. |
| 2011 | |
| 2012 | E.g.:: |
| 2013 | |
| 2014 | stmt = select(Address).where(with_parent(some_user, User.addresses)) |
| 2015 | |
| 2016 | The SQL rendered is the same as that rendered when a lazy loader |
| 2017 | would fire off from the given parent on that attribute, meaning |
| 2018 | that the appropriate state is taken from the parent object in |
| 2019 | Python without the need to render joins to the parent table |
| 2020 | in the rendered statement. |
| 2021 | |
| 2022 | The given property may also make use of :meth:`_orm.PropComparator.of_type` |
| 2023 | to indicate the left side of the criteria:: |
| 2024 | |
| 2025 | |
| 2026 | a1 = aliased(Address) |
| 2027 | a2 = aliased(Address) |
| 2028 | stmt = select(a1, a2).where(with_parent(u1, User.addresses.of_type(a2))) |
| 2029 | |
| 2030 | The above use is equivalent to using the |
| 2031 | :func:`_orm.with_parent.from_entity` argument:: |
| 2032 | |
| 2033 | a1 = aliased(Address) |
| 2034 | a2 = aliased(Address) |
| 2035 | stmt = select(a1, a2).where( |
| 2036 | with_parent(u1, User.addresses, from_entity=a2) |
| 2037 | ) |
| 2038 | |
| 2039 | :param instance: |
| 2040 | An instance which has some :func:`_orm.relationship`. |
| 2041 | |
| 2042 | :param property: |
| 2043 | Class-bound attribute, which indicates |
| 2044 | what relationship from the instance should be used to reconcile the |
| 2045 | parent/child relationship. |
| 2046 | |
| 2047 | :param from_entity: |
| 2048 | Entity in which to consider as the left side. This defaults to the |
| 2049 | "zero" entity of the :class:`_query.Query` itself. |
| 2050 | |
| 2051 | """ # noqa: E501 |
| 2052 | prop_t: RelationshipProperty[Any] |
| 2053 | |
| 2054 | if isinstance(prop, str): |
| 2055 | raise sa_exc.ArgumentError( |
| 2056 | "with_parent() accepts class-bound mapped attributes, not strings" |
| 2057 | ) |
| 2058 | elif isinstance(prop, attributes.QueryableAttribute): |
| 2059 | if prop._of_type: |