Association Proxy

associationproxy is used to create a read/write view of a target attribute across a relationship. It essentially conceals the usage of a “middle” attribute between two endpoints, and can be used to cherry-pick fields from a collection of related objects or to reduce the verbosity of using the association object pattern. Applied creatively, the association proxy allows the construction of sophisticated collections and dictionary views of virtually any geometry, persisted to the database using standard, transparently configured relational patterns.

Simplifying Scalar Collections

Consider a many-to-many mapping between two classes, User and Keyword. Each User can have any number of Keyword objects, and vice-versa (the many-to-many pattern is described at Many To Many):

  1. from sqlalchemy import Column, Integer, String, ForeignKey, Table
  2. from sqlalchemy.orm import relationship
  3. from sqlalchemy.ext.declarative import declarative_base
  4. Base = declarative_base()
  5. class User(Base):
  6. __tablename__ = 'user'
  7. id = Column(Integer, primary_key=True)
  8. name = Column(String(64))
  9. kw = relationship("Keyword", secondary=lambda: userkeywords_table)
  10. def __init__(self, name):
  11. self.name = name
  12. class Keyword(Base):
  13. __tablename__ = 'keyword'
  14. id = Column(Integer, primary_key=True)
  15. keyword = Column('keyword', String(64))
  16. def __init__(self, keyword):
  17. self.keyword = keyword
  18. userkeywords_table = Table('userkeywords', Base.metadata,
  19. Column('user_id', Integer, ForeignKey("user.id"),
  20. primary_key=True),
  21. Column('keyword_id', Integer, ForeignKey("keyword.id"),
  22. primary_key=True)
  23. )

Reading and manipulating the collection of “keyword” strings associated with User requires traversal from each collection element to the .keyword attribute, which can be awkward:

  1. >>> user = User('jek')
  2. >>> user.kw.append(Keyword('cheese inspector'))
  3. >>> print(user.kw)
  4. [<__main__.Keyword object at 0x12bf830>]
  5. >>> print(user.kw[0].keyword)
  6. cheese inspector
  7. >>> print([keyword.keyword for keyword in user.kw])
  8. ['cheese inspector']

The association_proxy is applied to the User class to produce a “view” of the kw relationship, which only exposes the string value of .keyword associated with each Keyword object:

  1. from sqlalchemy.ext.associationproxy import association_proxy
  2. class User(Base):
  3. __tablename__ = 'user'
  4. id = Column(Integer, primary_key=True)
  5. name = Column(String(64))
  6. kw = relationship("Keyword", secondary=lambda: userkeywords_table)
  7. def __init__(self, name):
  8. self.name = name
  9. # proxy the 'keyword' attribute from the 'kw' relationship
  10. keywords = association_proxy('kw', 'keyword')

We can now reference the .keywords collection as a listing of strings, which is both readable and writable. New Keyword objects are created for us transparently:

  1. >>> user = User('jek')
  2. >>> user.keywords.append('cheese inspector')
  3. >>> user.keywords
  4. ['cheese inspector']
  5. >>> user.keywords.append('snack ninja')
  6. >>> user.kw
  7. [<__main__.Keyword object at 0x12cdd30>, <__main__.Keyword object at 0x12cde30>]

The AssociationProxy object produced by the association_proxy() function is an instance of a Python descriptor. It is always declared with the user-defined class being mapped, regardless of whether Declarative or classical mappings via the mapper() function are used.

The proxy functions by operating upon the underlying mapped attribute or collection in response to operations, and changes made via the proxy are immediately apparent in the mapped attribute, as well as vice versa. The underlying attribute remains fully accessible.

When first accessed, the association proxy performs introspection operations on the target collection so that its behavior corresponds correctly. Details such as if the locally proxied attribute is a collection (as is typical) or a scalar reference, as well as if the collection acts like a set, list, or dictionary is taken into account, so that the proxy should act just like the underlying collection or attribute does.

Creation of New Values

When a list append() event (or set add(), dictionary __setitem__(), or scalar assignment event) is intercepted by the association proxy, it instantiates a new instance of the “intermediary” object using its constructor, passing as a single argument the given value. In our example above, an operation like:

  1. user.keywords.append('cheese inspector')

Is translated by the association proxy into the operation:

  1. user.kw.append(Keyword('cheese inspector'))

The example works here because we have designed the constructor for Keyword to accept a single positional argument, keyword. For those cases where a single-argument constructor isn’t feasible, the association proxy’s creational behavior can be customized using the creator argument, which references a callable (i.e. Python function) that will produce a new object instance given the singular argument. Below we illustrate this using a lambda as is typical:

  1. class User(Base):
  2. # ...
  3. # use Keyword(keyword=kw) on append() events
  4. keywords = association_proxy('kw', 'keyword',
  5. creator=lambda kw: Keyword(keyword=kw))

The creator function accepts a single argument in the case of a list- or set- based collection, or a scalar attribute. In the case of a dictionary-based collection, it accepts two arguments, “key” and “value”. An example of this is below in Proxying to Dictionary Based Collections.

Simplifying Association Objects

The “association object” pattern is an extended form of a many-to-many relationship, and is described at Association Object. Association proxies are useful for keeping “association objects” out of the way during regular use.

Suppose our userkeywords table above had additional columns which we’d like to map explicitly, but in most cases we don’t require direct access to these attributes. Below, we illustrate a new mapping which introduces the UserKeyword class, which is mapped to the userkeywords table illustrated earlier. This class adds an additional column special_key, a value which we occasionally want to access, but not in the usual case. We create an association proxy on the User class called keywords, which will bridge the gap from the user_keywords collection of User to the .keyword attribute present on each UserKeyword:

  1. from sqlalchemy import Column, Integer, String, ForeignKey
  2. from sqlalchemy.orm import relationship, backref
  3. from sqlalchemy.ext.associationproxy import association_proxy
  4. from sqlalchemy.ext.declarative import declarative_base
  5. Base = declarative_base()
  6. class User(Base):
  7. __tablename__ = 'user'
  8. id = Column(Integer, primary_key=True)
  9. name = Column(String(64))
  10. # association proxy of "user_keywords" collection
  11. # to "keyword" attribute
  12. keywords = association_proxy('user_keywords', 'keyword')
  13. def __init__(self, name):
  14. self.name = name
  15. class UserKeyword(Base):
  16. __tablename__ = 'user_keyword'
  17. user_id = Column(Integer, ForeignKey('user.id'), primary_key=True)
  18. keyword_id = Column(Integer, ForeignKey('keyword.id'), primary_key=True)
  19. special_key = Column(String(50))
  20. # bidirectional attribute/collection of "user"/"user_keywords"
  21. user = relationship(User,
  22. backref=backref("user_keywords",
  23. cascade="all, delete-orphan")
  24. )
  25. # reference to the "Keyword" object
  26. keyword = relationship("Keyword")
  27. def __init__(self, keyword=None, user=None, special_key=None):
  28. self.user = user
  29. self.keyword = keyword
  30. self.special_key = special_key
  31. class Keyword(Base):
  32. __tablename__ = 'keyword'
  33. id = Column(Integer, primary_key=True)
  34. keyword = Column('keyword', String(64))
  35. def __init__(self, keyword):
  36. self.keyword = keyword
  37. def __repr__(self):
  38. return 'Keyword(%s)' % repr(self.keyword)

With the above configuration, we can operate upon the .keywords collection of each User object, and the usage of UserKeyword is concealed:

  1. >>> user = User('log')
  2. >>> for kw in (Keyword('new_from_blammo'), Keyword('its_big')):
  3. ... user.keywords.append(kw)
  4. ...
  5. >>> print(user.keywords)
  6. [Keyword('new_from_blammo'), Keyword('its_big')]

Where above, each .keywords.append() operation is equivalent to:

  1. >>> user.user_keywords.append(UserKeyword(Keyword('its_heavy')))

The UserKeyword association object has two attributes here which are populated; the .keyword attribute is populated directly as a result of passing the Keyword object as the first argument. The .user argument is then assigned as the UserKeyword object is appended to the User.user_keywords collection, where the bidirectional relationship configured between User.user_keywords and UserKeyword.user results in a population of the UserKeyword.user attribute. The special_key argument above is left at its default value of None.

For those cases where we do want special_key to have a value, we create the UserKeyword object explicitly. Below we assign all three attributes, where the assignment of .user has the effect of the UserKeyword being appended to the User.user_keywords collection:

  1. >>> UserKeyword(Keyword('its_wood'), user, special_key='my special key')

The association proxy returns to us a collection of Keyword objects represented by all these operations:

  1. >>> user.keywords
  2. [Keyword('new_from_blammo'), Keyword('its_big'), Keyword('its_heavy'), Keyword('its_wood')]

Proxying to Dictionary Based Collections

The association proxy can proxy to dictionary based collections as well. SQLAlchemy mappings usually use the attribute_mapped_collection() collection type to create dictionary collections, as well as the extended techniques described in Custom Dictionary-Based Collections.

The association proxy adjusts its behavior when it detects the usage of a dictionary-based collection. When new values are added to the dictionary, the association proxy instantiates the intermediary object by passing two arguments to the creation function instead of one, the key and the value. As always, this creation function defaults to the constructor of the intermediary class, and can be customized using the creator argument.

Below, we modify our UserKeyword example such that the User.user_keywords collection will now be mapped using a dictionary, where the UserKeyword.special_key argument will be used as the key for the dictionary. We then apply a creator argument to the User.keywords proxy so that these values are assigned appropriately when new elements are added to the dictionary:

  1. from sqlalchemy import Column, Integer, String, ForeignKey
  2. from sqlalchemy.orm import relationship, backref
  3. from sqlalchemy.ext.associationproxy import association_proxy
  4. from sqlalchemy.ext.declarative import declarative_base
  5. from sqlalchemy.orm.collections import attribute_mapped_collection
  6. Base = declarative_base()
  7. class User(Base):
  8. __tablename__ = 'user'
  9. id = Column(Integer, primary_key=True)
  10. name = Column(String(64))
  11. # proxy to 'user_keywords', instantiating UserKeyword
  12. # assigning the new key to 'special_key', values to
  13. # 'keyword'.
  14. keywords = association_proxy('user_keywords', 'keyword',
  15. creator=lambda k, v:
  16. UserKeyword(special_key=k, keyword=v)
  17. )
  18. def __init__(self, name):
  19. self.name = name
  20. class UserKeyword(Base):
  21. __tablename__ = 'user_keyword'
  22. user_id = Column(Integer, ForeignKey('user.id'), primary_key=True)
  23. keyword_id = Column(Integer, ForeignKey('keyword.id'), primary_key=True)
  24. special_key = Column(String)
  25. # bidirectional user/user_keywords relationships, mapping
  26. # user_keywords with a dictionary against "special_key" as key.
  27. user = relationship(User, backref=backref(
  28. "user_keywords",
  29. collection_class=attribute_mapped_collection("special_key"),
  30. cascade="all, delete-orphan"
  31. )
  32. )
  33. keyword = relationship("Keyword")
  34. class Keyword(Base):
  35. __tablename__ = 'keyword'
  36. id = Column(Integer, primary_key=True)
  37. keyword = Column('keyword', String(64))
  38. def __init__(self, keyword):
  39. self.keyword = keyword
  40. def __repr__(self):
  41. return 'Keyword(%s)' % repr(self.keyword)

We illustrate the .keywords collection as a dictionary, mapping the UserKeyword.special_key value to Keyword objects:

  1. >>> user = User('log')
  2. >>> user.keywords['sk1'] = Keyword('kw1')
  3. >>> user.keywords['sk2'] = Keyword('kw2')
  4. >>> print(user.keywords)
  5. {'sk1': Keyword('kw1'), 'sk2': Keyword('kw2')}

Composite Association Proxies

Given our previous examples of proxying from relationship to scalar attribute, proxying across an association object, and proxying dictionaries, we can combine all three techniques together to give User a keywords dictionary that deals strictly with the string value of special_key mapped to the string keyword. Both the UserKeyword and Keyword classes are entirely concealed. This is achieved by building an association proxy on User that refers to an association proxy present on UserKeyword:

  1. from sqlalchemy import Column, Integer, String, ForeignKey
  2. from sqlalchemy.orm import relationship, backref
  3. from sqlalchemy.ext.associationproxy import association_proxy
  4. from sqlalchemy.ext.declarative import declarative_base
  5. from sqlalchemy.orm.collections import attribute_mapped_collection
  6. Base = declarative_base()
  7. class User(Base):
  8. __tablename__ = 'user'
  9. id = Column(Integer, primary_key=True)
  10. name = Column(String(64))
  11. # the same 'user_keywords'->'keyword' proxy as in
  12. # the basic dictionary example.
  13. keywords = association_proxy(
  14. 'user_keywords',
  15. 'keyword',
  16. creator=lambda k, v: UserKeyword(special_key=k, keyword=v)
  17. )
  18. # another proxy that is directly column-targeted
  19. special_keys = association_proxy("user_keywords", "special_key")
  20. def __init__(self, name):
  21. self.name = name
  22. class UserKeyword(Base):
  23. __tablename__ = 'user_keyword'
  24. user_id = Column(ForeignKey('user.id'), primary_key=True)
  25. keyword_id = Column(ForeignKey('keyword.id'), primary_key=True)
  26. special_key = Column(String)
  27. user = relationship(
  28. User,
  29. backref=backref(
  30. "user_keywords",
  31. collection_class=attribute_mapped_collection("special_key"),
  32. cascade="all, delete-orphan"
  33. )
  34. )
  35. # the relationship to Keyword is now called
  36. # 'kw'
  37. kw = relationship("Keyword")
  38. # 'keyword' is changed to be a proxy to the
  39. # 'keyword' attribute of 'Keyword'
  40. keyword = association_proxy('kw', 'keyword')
  41. class Keyword(Base):
  42. __tablename__ = 'keyword'
  43. id = Column(Integer, primary_key=True)
  44. keyword = Column('keyword', String(64))
  45. def __init__(self, keyword):
  46. self.keyword = keyword

User.keywords is now a dictionary of string to string, where UserKeyword and Keyword objects are created and removed for us transparently using the association proxy. In the example below, we illustrate usage of the assignment operator, also appropriately handled by the association proxy, to apply a dictionary value to the collection at once:

  1. >>> user = User('log')
  2. >>> user.keywords = {
  3. ... 'sk1':'kw1',
  4. ... 'sk2':'kw2'
  5. ... }
  6. >>> print(user.keywords)
  7. {'sk1': 'kw1', 'sk2': 'kw2'}
  8. >>> user.keywords['sk3'] = 'kw3'
  9. >>> del user.keywords['sk2']
  10. >>> print(user.keywords)
  11. {'sk1': 'kw1', 'sk3': 'kw3'}
  12. >>> # illustrate un-proxied usage
  13. ... print(user.user_keywords['sk3'].kw)
  14. <__main__.Keyword object at 0x12ceb90>

One caveat with our example above is that because Keyword objects are created for each dictionary set operation, the example fails to maintain uniqueness for the Keyword objects on their string name, which is a typical requirement for a tagging scenario such as this one. For this use case the recipe UniqueObject, or a comparable creational strategy, is recommended, which will apply a “lookup first, then create” strategy to the constructor of the Keyword class, so that an already existing Keyword is returned if the given name is already present.

Querying with Association Proxies

The AssociationProxy features simple SQL construction capabilities which work at the class level in a similar way as other ORM-mapped attributes. Class-bound attributes such as User.keywords and User.special_keys in the preceding example will provide for a SQL generating construct when accessed at the class level.

Note

The primary purpose of the association proxy extension is to allow for improved persistence and object-access patterns with mapped object instances that are already loaded. The class-bound querying feature is of limited use and will not replace the need to refer to the underlying attributes when constructing SQL queries with JOINs, eager loading options, etc.

The SQL generated takes the form of a correlated subquery against the EXISTS SQL operator so that it can be used in a WHERE clause without the need for additional modifications to the enclosing query. If the immediate target of an association proxy is a mapped column expression, standard column operators can be used which will be embedded in the subquery. For example a straight equality operator:

  1. >>> print(session.query(User).filter(User.special_keys == "jek"))
  2. SELECT "user".id AS user_id, "user".name AS user_name
  3. FROM "user"
  4. WHERE EXISTS (SELECT 1
  5. FROM user_keyword
  6. WHERE "user".id = user_keyword.user_id AND user_keyword.special_key = :special_key_1)

a LIKE operator:

  1. >>> print(session.query(User).filter(User.special_keys.like("%jek")))
  2. SELECT "user".id AS user_id, "user".name AS user_name
  3. FROM "user"
  4. WHERE EXISTS (SELECT 1
  5. FROM user_keyword
  6. WHERE "user".id = user_keyword.user_id AND user_keyword.special_key LIKE :special_key_1)

For association proxies where the immediate target is a related object or collection, or another association proxy or attribute on the related object, relationship-oriented operators can be used instead, such as PropComparator.has() and PropComparator.any(). The User.keywords attribute is in fact two association proxies linked together, so when using this proxy for generating SQL phrases, we get two levels of EXISTS subqueries:

  1. >>> print(session.query(User).filter(User.keywords.any(Keyword.keyword == "jek")))
  2. SELECT "user".id AS user_id, "user".name AS user_name
  3. FROM "user"
  4. WHERE EXISTS (SELECT 1
  5. FROM user_keyword
  6. WHERE "user".id = user_keyword.user_id AND (EXISTS (SELECT 1
  7. FROM keyword
  8. WHERE keyword.id = user_keyword.keyword_id AND keyword.keyword = :keyword_1)))

This is not the most efficient form of SQL, so while association proxies can be convenient for generating WHERE criteria quickly, SQL results should be inspected and “unrolled” into explicit JOIN criteria for best use, especially when chaining association proxies together.

Changed in version 1.3: Association proxy features distinct querying modes based on the type of target. See AssociationProxy now provides standard column operators for a column-oriented target.

Cascading Scalar Deletes

New in version 1.3.

Given a mapping as:

  1. class A(Base):
  2. __tablename__ = 'test_a'
  3. id = Column(Integer, primary_key=True)
  4. ab = relationship(
  5. 'AB', backref='a', uselist=False)
  6. b = association_proxy(
  7. 'ab', 'b', creator=lambda b: AB(b=b),
  8. cascade_scalar_deletes=True)
  9. class B(Base):
  10. __tablename__ = 'test_b'
  11. id = Column(Integer, primary_key=True)
  12. ab = relationship('AB', backref='b', cascade='all, delete-orphan')
  13. class AB(Base):
  14. __tablename__ = 'test_ab'
  15. a_id = Column(Integer, ForeignKey(A.id), primary_key=True)
  16. b_id = Column(Integer, ForeignKey(B.id), primary_key=True)

An assignment to A.b will generate an AB object:

  1. a.b = B()

The A.b association is scalar, and includes use of the flag AssociationProxy.cascade_scalar_deletes. When set, setting A.b to None will remove A.ab as well:

  1. a.b = None
  2. assert a.ab is None

When AssociationProxy.cascade_scalar_deletes is not set, the association object a.ab above would remain in place.

Note that this is not the behavior for collection-based association proxies; in that case, the intermediary association object is always removed when members of the proxied collection are removed. Whether or not the row is deleted depends on the relationship cascade setting.

See also

Cascades

API Documentation

Object NameDescription

association_proxy(target_collection, attr, **kw)

Return a Python property implementing a view of a target attribute which references an attribute on members of the target.

ASSOCIATION_PROXY

AssociationProxy

A descriptor that presents a read/write view of an object attribute.

AssociationProxyInstance

A per-class object that serves class- and object-specific results.

ColumnAssociationProxyInstance

an AssociationProxyInstance that has a database column as a target.

ObjectAssociationProxyInstance

an AssociationProxyInstance that has an object as a target.

function sqlalchemy.ext.associationproxy.``association_proxy(target_collection, attr, \*kw*)

Return a Python property implementing a view of a target attribute which references an attribute on members of the target.

The returned value is an instance of AssociationProxy.

Implements a Python property representing a relationship as a collection of simpler values, or a scalar value. The proxied property will mimic the collection type of the target (list, dict or set), or, in the case of a one to one relationship, a simple scalar value.

  • Parameters

    • target_collection – Name of the attribute we’ll proxy to. This attribute is typically mapped by relationship() to link to a target collection, but can also be a many-to-one or non-scalar relationship.

    • attr

      Attribute on the associated instance or instances we’ll proxy for.

      For example, given a target collection of [obj1, obj2], a list created by this proxy property would look like [getattr(obj1, attr), getattr(obj2, attr)]

      If the relationship is one-to-one or otherwise uselist=False, then simply: getattr(obj, attr)

    • creator

      optional.

      When new items are added to this proxied collection, new instances of the class collected by the target collection will be created. For list and set collections, the target class constructor will be called with the ‘value’ for the new instance. For dict types, two arguments are passed: key and value.

      If you want to construct instances differently, supply a creator function that takes arguments as above and returns instances.

      For scalar relationships, creator() will be called if the target is None. If the target is present, set operations are proxied to setattr() on the associated object.

      If you have an associated object with multiple attributes, you may set up multiple association proxies mapping to different attributes. See the unit tests for examples, and for examples of how creator() functions can be used to construct the scalar relationship on-demand in this situation.

    • **kw – Passes along any other keyword arguments to AssociationProxy.

class sqlalchemy.ext.associationproxy.``AssociationProxy(target_collection, attr, creator=None, getset_factory=None, proxy_factory=None, proxy_bulk_set=None, info=None, cascade_scalar_deletes=False)

A descriptor that presents a read/write view of an object attribute.

Class signature

class sqlalchemy.ext.associationproxy.AssociationProxy (sqlalchemy.orm.base.InspectionAttrInfo)

  • method sqlalchemy.ext.associationproxy.AssociationProxy.__init__(target_collection, attr, creator=None, getset_factory=None, proxy_factory=None, proxy_bulk_set=None, info=None, cascade_scalar_deletes=False)

    Construct a new AssociationProxy.

    The association_proxy() function is provided as the usual entrypoint here, though AssociationProxy can be instantiated and/or subclassed directly.

    • Parameters

      • target_collection – Name of the collection we’ll proxy to, usually created with relationship().

      • attr – Attribute on the collected instances we’ll proxy for. For example, given a target collection of [obj1, obj2], a list created by this proxy property would look like [getattr(obj1, attr), getattr(obj2, attr)]

      • creator

        Optional. When new items are added to this proxied collection, new instances of the class collected by the target collection will be created. For list and set collections, the target class constructor will be called with the ‘value’ for the new instance. For dict types, two arguments are passed: key and value.

        If you want to construct instances differently, supply a ‘creator’ function that takes arguments as above and returns instances.

      • cascade_scalar_deletes

        when True, indicates that setting the proxied value to None, or deleting it via del, should also remove the source object. Only applies to scalar attributes. Normally, removing the proxied target will not remove the proxy source, as this object may have other state that is still to be kept.

        New in version 1.3.

        See also

        Cascading Scalar Deletes - complete usage example

      • getset_factory

        Optional. Proxied attribute access is automatically handled by routines that get and set values based on the attr argument for this proxy.

        If you would like to customize this behavior, you may supply a getset_factory callable that produces a tuple of getter and setter functions. The factory is called with two arguments, the abstract type of the underlying collection and this proxy instance.

      • proxy_factory – Optional. The type of collection to emulate is determined by sniffing the target collection. If your collection type can’t be determined by duck typing or you’d like to use a different collection implementation, you may supply a factory function to produce those collections. Only applicable to non-scalar relationships.

      • proxy_bulk_set – Optional, use with proxy_factory. See the _set() method for details.

      • info

        optional, will be assigned to AssociationProxy.info if present.

        New in version 1.0.9.

  1. New in version 1.3: - [`AssociationProxy`](#sqlalchemy.ext.associationproxy.AssociationProxy "sqlalchemy.ext.associationproxy.AssociationProxy") no longer stores any state specific to a particular parent class; the state is now stored in per-class [`AssociationProxyInstance`](#sqlalchemy.ext.associationproxy.AssociationProxyInstance "sqlalchemy.ext.associationproxy.AssociationProxyInstance") objects.

class sqlalchemy.ext.associationproxy.``AssociationProxyInstance(parent, owning_class, target_class, value_attr)

A per-class object that serves class- and object-specific results.

This is used by AssociationProxy when it is invoked in terms of a specific class or instance of a class, i.e. when it is used as a regular Python descriptor.

When referring to the AssociationProxy as a normal Python descriptor, the AssociationProxyInstance is the object that actually serves the information. Under normal circumstances, its presence is transparent:

  1. >>> User.keywords.scalar
  2. False

In the special case that the AssociationProxy object is being accessed directly, in order to get an explicit handle to the AssociationProxyInstance, use the AssociationProxy.for_class() method:

  1. proxy_state = inspect(User).all_orm_descriptors["keywords"].for_class(User)
  2. # view if proxy object is scalar or not
  3. >>> proxy_state.scalar
  4. False

New in version 1.3.

class sqlalchemy.ext.associationproxy.``ObjectAssociationProxyInstance(parent, owning_class, target_class, value_attr)

an AssociationProxyInstance that has an object as a target.

Class signature

class sqlalchemy.ext.associationproxy.ObjectAssociationProxyInstance (sqlalchemy.ext.associationproxy.AssociationProxyInstance)

class sqlalchemy.ext.associationproxy.``ColumnAssociationProxyInstance(parent, owning_class, target_class, value_attr)

an AssociationProxyInstance that has a database column as a target.

Class signature

class sqlalchemy.ext.associationproxy.ColumnAssociationProxyInstance (sqlalchemy.sql.expression.ColumnOperators, sqlalchemy.ext.associationproxy.AssociationProxyInstance)

  1. See also
  2. [`ColumnOperators.startswith()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnOperators.startswith "sqlalchemy.sql.expression.ColumnOperators.startswith")
  3. [`ColumnOperators.endswith()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnOperators.endswith "sqlalchemy.sql.expression.ColumnOperators.endswith")
  4. [`ColumnOperators.like()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnOperators.like "sqlalchemy.sql.expression.ColumnOperators.like")
  • method sqlalchemy.ext.associationproxy.ColumnAssociationProxyInstance.desc()

    inherited from the ColumnOperators.desc() method of ColumnOperators

    Produce a desc() clause against the parent object.

  • method sqlalchemy.ext.associationproxy.ColumnAssociationProxyInstance.distinct()

    inherited from the ColumnOperators.distinct() method of ColumnOperators

    Produce a distinct() clause against the parent object.

  • method sqlalchemy.ext.associationproxy.ColumnAssociationProxyInstance.endswith(other, \*kwargs*)

    inherited from the ColumnOperators.endswith() method of ColumnOperators

    Implement the ‘endswith’ operator.

    Produces a LIKE expression that tests against a match for the end of a string value:

    1. column LIKE '%' || <other>

    E.g.:

    1. stmt = select(sometable).\
    2. where(sometable.c.column.endswith("foobar"))

    Since the operator uses LIKE, wildcard characters "%" and "_" that are present inside the <other> expression will behave like wildcards as well. For literal string values, the ColumnOperators.endswith.autoescape flag may be set to True to apply escaping to occurrences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the ColumnOperators.endswith.escape parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string.

    • Parameters

      • other – expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters % and _ are not escaped by default unless the ColumnOperators.endswith.autoescape flag is set to True.

      • autoescape

        boolean; when True, establishes an escape character within the LIKE expression, then applies it to all occurrences of "%", "_" and the escape character itself within the comparison value, which is assumed to be a literal string and not a SQL expression.

        An expression such as:

        1. somecolumn.endswith("foo%bar", autoescape=True)

        Will render as:

        1. somecolumn LIKE '%' || :param ESCAPE '/'

        With the value of :param as "foo/%bar".

      • escape

        a character which when given will render with the ESCAPE keyword to establish that character as the escape character. This character can then be placed preceding occurrences of % and _ to allow them to act as themselves and not wildcard characters.

        An expression such as:

        1. somecolumn.endswith("foo/%bar", escape="^")

        Will render as:

        1. somecolumn LIKE '%' || :param ESCAPE '^'

        The parameter may also be combined with ColumnOperators.endswith.autoescape:

        1. somecolumn.endswith("foo%bar^bat", escape="^", autoescape=True)

        Where above, the given literal parameter will be converted to "foo^%bar^^bat" before being passed to the database.

  1. See also
  2. [`ColumnOperators.startswith()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnOperators.startswith "sqlalchemy.sql.expression.ColumnOperators.startswith")
  3. [`ColumnOperators.contains()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnOperators.contains "sqlalchemy.sql.expression.ColumnOperators.contains")
  4. [`ColumnOperators.like()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnOperators.like "sqlalchemy.sql.expression.ColumnOperators.like")
  1. See also
  2. [`ColumnOperators.like()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnOperators.like "sqlalchemy.sql.expression.ColumnOperators.like")
  • method sqlalchemy.ext.associationproxy.ColumnAssociationProxyInstance.in_(other)

    inherited from the ColumnOperators.in_() method of ColumnOperators

    Implement the in operator.

    In a column context, produces the clause column IN <other>.

    The given parameter other may be:

    • A list of literal values, e.g.:

      1. stmt.where(column.in_([1, 2, 3]))

      In this calling form, the list of items is converted to a set of bound parameters the same length as the list given:

      1. WHERE COL IN (?, ?, ?)
    • A list of tuples may be provided if the comparison is against a tuple_() containing multiple expressions:

      1. from sqlalchemy import tuple_
      2. stmt.where(tuple_(col1, col2).in_([(1, 10), (2, 20), (3, 30)]))
    • An empty list, e.g.:

      1. stmt.where(column.in_([]))

      In this calling form, the expression renders an “empty set” expression. These expressions are tailored to individual backends and are generally trying to get an empty SELECT statement as a subquery. Such as on SQLite, the expression is:

      1. WHERE col IN (SELECT 1 FROM (SELECT 1) WHERE 1!=1)

      Changed in version 1.4: empty IN expressions now use an execution-time generated SELECT subquery in all cases.

    • A bound parameter, e.g. bindparam(), may be used if it includes the bindparam.expanding flag:

      1. stmt.where(column.in_(bindparam('value', expanding=True)))

      In this calling form, the expression renders a special non-SQL placeholder expression that looks like:

      1. WHERE COL IN ([EXPANDING_value])

      This placeholder expression is intercepted at statement execution time to be converted into the variable number of bound parameter form illustrated earlier. If the statement were executed as:

      1. connection.execute(stmt, {"value": [1, 2, 3]})

      The database would be passed a bound parameter for each value:

      1. WHERE COL IN (?, ?, ?)

      New in version 1.2: added “expanding” bound parameters

      If an empty list is passed, a special “empty list” expression, which is specific to the database in use, is rendered. On SQLite this would be:

      1. WHERE COL IN (SELECT 1 FROM (SELECT 1) WHERE 1!=1)

      New in version 1.3: “expanding” bound parameters now support empty lists

    • a select() construct, which is usually a correlated scalar select:

      1. stmt.where(
      2. column.in_(
      3. select(othertable.c.y).
      4. where(table.c.x == othertable.c.x)
      5. )
      6. )

      In this calling form, ColumnOperators.in_() renders as given:

      1. WHERE COL IN (SELECT othertable.y
      2. FROM othertable WHERE othertable.x = table.x)
    • Parameters

      other – a list of literals, a select() construct, or a bindparam() construct that includes the bindparam.expanding flag set to True.

  • method sqlalchemy.ext.associationproxy.ColumnAssociationProxyInstance.is_(other)

    inherited from the ColumnOperators.is_() method of ColumnOperators

    Implement the IS operator.

    Normally, IS is generated automatically when comparing to a value of None, which resolves to NULL. However, explicit usage of IS may be desirable if comparing to boolean values on certain platforms.

    See also

    ColumnOperators.is_not()

  • method sqlalchemy.ext.associationproxy.ColumnAssociationProxyInstance.is_distinct_from(other)

    inherited from the ColumnOperators.is_distinct_from() method of ColumnOperators

    Implement the IS DISTINCT FROM operator.

    Renders “a IS DISTINCT FROM b” on most platforms; on some such as SQLite may render “a IS NOT b”.

    New in version 1.1.

  • method sqlalchemy.ext.associationproxy.ColumnAssociationProxyInstance.is_not(other)

    inherited from the ColumnOperators.is_not() method of ColumnOperators

    Implement the IS NOT operator.

    Normally, IS NOT is generated automatically when comparing to a value of None, which resolves to NULL. However, explicit usage of IS NOT may be desirable if comparing to boolean values on certain platforms.

    Changed in version 1.4: The is_not() operator is renamed from isnot() in previous releases. The previous name remains available for backwards compatibility.

    See also

    ColumnOperators.is_()

  • method sqlalchemy.ext.associationproxy.ColumnAssociationProxyInstance.is_not_distinct_from(other)

    inherited from the ColumnOperators.is_not_distinct_from() method of ColumnOperators

    Implement the IS NOT DISTINCT FROM operator.

    Renders “a IS NOT DISTINCT FROM b” on most platforms; on some such as SQLite may render “a IS b”.

    Changed in version 1.4: The is_not_distinct_from() operator is renamed from isnot_distinct_from() in previous releases. The previous name remains available for backwards compatibility.

    New in version 1.1.

  • method sqlalchemy.ext.associationproxy.ColumnAssociationProxyInstance.isnot(other)

    inherited from the ColumnOperators.isnot() method of ColumnOperators

    Implement the IS NOT operator.

    Normally, IS NOT is generated automatically when comparing to a value of None, which resolves to NULL. However, explicit usage of IS NOT may be desirable if comparing to boolean values on certain platforms.

    Changed in version 1.4: The is_not() operator is renamed from isnot() in previous releases. The previous name remains available for backwards compatibility.

    See also

    ColumnOperators.is_()

  • method sqlalchemy.ext.associationproxy.ColumnAssociationProxyInstance.isnot_distinct_from(other)

    inherited from the ColumnOperators.isnot_distinct_from() method of ColumnOperators

    Implement the IS NOT DISTINCT FROM operator.

    Renders “a IS NOT DISTINCT FROM b” on most platforms; on some such as SQLite may render “a IS b”.

    Changed in version 1.4: The is_not_distinct_from() operator is renamed from isnot_distinct_from() in previous releases. The previous name remains available for backwards compatibility.

    New in version 1.1.

  • method sqlalchemy.ext.associationproxy.ColumnAssociationProxyInstance.like(other, escape=None)

    inherited from the ColumnOperators.like() method of ColumnOperators

    Implement the like operator.

    In a column context, produces the expression:

    1. a LIKE other

    E.g.:

    1. stmt = select(sometable).\
    2. where(sometable.c.column.like("%foobar%"))
    • Parameters

      • other – expression to be compared

      • escape

        optional escape character, renders the ESCAPE keyword, e.g.:

        1. somecolumn.like("foo/%bar", escape="/")
  1. See also
  2. [`ColumnOperators.ilike()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnOperators.ilike "sqlalchemy.sql.expression.ColumnOperators.ilike")
  1. See also
  2. [Redefining and Creating New Operators]($993b6f7a0d78cd7b.md#types-operators)
  3. [Using custom operators in join conditions]($e1f42b7742e49253.md#relationship-custom-operator)
  • method sqlalchemy.ext.associationproxy.ColumnAssociationProxyInstance.operate(op, \other, **kwargs*)

    Operate on an argument.

    This is the lowest level of operation, raises NotImplementedError by default.

    Overriding this on a subclass can allow common behavior to be applied to all operations. For example, overriding ColumnOperators to apply func.lower() to the left and right side:

    1. class MyComparator(ColumnOperators):
    2. def operate(self, op, other):
    3. return op(func.lower(self), func.lower(other))
    • Parameters

      • op – Operator callable.

      • *other – the ‘other’ side of the operation. Will be a single scalar for most operations.

      • **kwargs – modifiers. These may be passed by special operators such as ColumnOperators.contains().

  • method sqlalchemy.ext.associationproxy.ColumnAssociationProxyInstance.regexp_match(pattern, flags=None)

    inherited from the ColumnOperators.regexp_match() method of ColumnOperators

    Implements a database-specific ‘regexp match’ operator.

    E.g.:

    1. stmt = select(table.c.some_column).where(
    2. table.c.some_column.regexp_match('^(b|c)')
    3. )

    ColumnOperators.regexp_match() attempts to resolve to a REGEXP-like function or operator provided by the backend, however the specific regular expression syntax and flags available are not backend agnostic.

    Examples include:

    • PostgreSQL - renders x ~ y or x !~ y when negated.

    • Oracle - renders REGEXP_LIKE(x, y)

    • SQLite - uses SQLite’s REGEXP placeholder operator and calls into the Python re.match() builtin.

    • other backends may provide special implementations.

    • Backends without any special implementation will emit the operator as “REGEXP” or “NOT REGEXP”. This is compatible with SQLite and MySQL, for example.

    Regular expression support is currently implemented for Oracle, PostgreSQL, MySQL and MariaDB. Partial support is available for SQLite. Support among third-party dialects may vary.

    • Parameters

      • pattern – The regular expression pattern string or column clause.

      • flags – Any regular expression string flags to apply. Flags tend to be backend specific. It can be a string or a column clause. Some backends, like PostgreSQL and MariaDB, may alternatively specify the flags as part of the pattern. When using the ignore case flag ‘i’ in PostgreSQL, the ignore case regexp match operator ~* or !~* will be used.

  1. New in version 1.4.
  2. See also
  3. [`ColumnOperators.regexp_replace()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnOperators.regexp_replace "sqlalchemy.sql.expression.ColumnOperators.regexp_replace")
  • method sqlalchemy.ext.associationproxy.ColumnAssociationProxyInstance.regexp_replace(pattern, replacement, flags=None)

    inherited from the ColumnOperators.regexp_replace() method of ColumnOperators

    Implements a database-specific ‘regexp replace’ operator.

    E.g.:

    1. stmt = select(
    2. table.c.some_column.regexp_replace(
    3. 'b(..)',
    4. 'XY',
    5. flags='g'
    6. )
    7. )

    ColumnOperators.regexp_replace() attempts to resolve to a REGEXP_REPLACE-like function provided by the backend, that usually emit the function REGEXP_REPLACE(). However, the specific regular expression syntax and flags available are not backend agnostic.

    Regular expression replacement support is currently implemented for Oracle, PostgreSQL, MySQL 8 or greater and MariaDB. Support among third-party dialects may vary.

    • Parameters

      • pattern – The regular expression pattern string or column clause.

      • pattern – The replacement string or column clause.

      • flags – Any regular expression string flags to apply. Flags tend to be backend specific. It can be a string or a column clause. Some backends, like PostgreSQL and MariaDB, may alternatively specify the flags as part of the pattern.

  1. New in version 1.4.
  2. See also
  3. [`ColumnOperators.regexp_match()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnOperators.regexp_match "sqlalchemy.sql.expression.ColumnOperators.regexp_match")
  1. See also
  2. [`ColumnOperators.endswith()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnOperators.endswith "sqlalchemy.sql.expression.ColumnOperators.endswith")
  3. [`ColumnOperators.contains()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnOperators.contains "sqlalchemy.sql.expression.ColumnOperators.contains")
  4. [`ColumnOperators.like()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnOperators.like "sqlalchemy.sql.expression.ColumnOperators.like")

sqlalchemy.ext.associationproxy.``ASSOCIATION_PROXY = symbol(‘ASSOCIATION_PROXY’)

Is assigned to the InspectionAttr.extension_type attribute.