Association Proxy
associationproxy
is used to create a read/write view of atarget attribute across a relationship. It essentially concealsthe usage of a “middle” attribute between two endpoints, andcan be used to cherry-pick fields from a collection ofrelated objects or to reduce the verbosity of using the associationobject pattern. Applied creatively, the association proxy allowsthe construction of sophisticated collections and dictionaryviews of virtually any geometry, persisted to the database usingstandard, 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):
- from sqlalchemy import Column, Integer, String, ForeignKey, Table
- from sqlalchemy.orm import relationship
- from sqlalchemy.ext.declarative import declarative_base
- Base = declarative_base()
- class User(Base):
- __tablename__ = 'user'
- id = Column(Integer, primary_key=True)
- name = Column(String(64))
- kw = relationship("Keyword", secondary=lambda: userkeywords_table)
- def __init__(self, name):
- self.name = name
- class Keyword(Base):
- __tablename__ = 'keyword'
- id = Column(Integer, primary_key=True)
- keyword = Column('keyword', String(64))
- def __init__(self, keyword):
- self.keyword = keyword
- userkeywords_table = Table('userkeywords', Base.metadata,
- Column('user_id', Integer, ForeignKey("user.id"),
- primary_key=True),
- Column('keyword_id', Integer, ForeignKey("keyword.id"),
- primary_key=True)
- )
Reading and manipulating the collection of “keyword” strings associatedwith User
requires traversal from each collection element to the .keyword
attribute, which can be awkward:
- >>> user = User('jek')
- >>> user.kw.append(Keyword('cheese inspector'))
- >>> print(user.kw)
- [<__main__.Keyword object at 0x12bf830>]
- >>> print(user.kw[0].keyword)
- cheese inspector
- >>> print([keyword.keyword for keyword in user.kw])
- ['cheese inspector']
The association_proxy
is applied to the User
class to producea “view” of the kw
relationship, which only exposes the stringvalue of .keyword
associated with each Keyword
object:
- from sqlalchemy.ext.associationproxy import association_proxy
- class User(Base):
- __tablename__ = 'user'
- id = Column(Integer, primary_key=True)
- name = Column(String(64))
- kw = relationship("Keyword", secondary=lambda: userkeywords_table)
- def __init__(self, name):
- self.name = name
- # proxy the 'keyword' attribute from the 'kw' relationship
- 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 createdfor us transparently:
- >>> user = User('jek')
- >>> user.keywords.append('cheese inspector')
- >>> user.keywords
- ['cheese inspector']
- >>> user.keywords.append('snack ninja')
- >>> user.kw
- [<__main__.Keyword object at 0x12cdd30>, <__main__.Keyword object at 0x12cde30>]
The AssociationProxy
object produced by the association_proxy()
functionis an instance of a Python descriptor.It is always declared with the user-defined class being mapped, regardless ofwhether Declarative or classical mappings via the mapper()
function are used.
The proxy functions by operating upon the underlying mapped attributeor collection in response to operations, and changes made via the proxy are immediatelyapparent in the mapped attribute, as well as vice versa. The underlyingattribute remains fully accessible.
When first accessed, the association proxy performs introspectionoperations 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 likethe underlying collection or attribute does.
Creation of New Values
When a list append() event (or set add(), dictionary setitem(), or scalarassignment event) is intercepted by the association proxy, it instantiates anew instance of the “intermediary” object using its constructor, passing as asingle argument the given value. In our example above, an operation like:
- user.keywords.append('cheese inspector')
Is translated by the association proxy into the operation:
- 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 asingle-argument constructor isn’t feasible, the association proxy’s creationalbehavior can be customized using the creator
argument, which references acallable (i.e. Python function) that will produce a new object instance given thesingular argument. Below we illustrate this using a lambda as is typical:
- class User(Base):
- # ...
- # use Keyword(keyword=kw) on append() events
- keywords = association_proxy('kw', 'keyword',
- 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-basedcollection, it accepts two arguments, “key” and “value”. An exampleof this is below in Proxying to Dictionary Based Collections.
Simplifying Association Objects
The “association object” pattern is an extended form of a many-to-manyrelationship, and is described at Association Object. Associationproxies are useful for keeping “association objects” out of the way duringregular use.
Suppose our userkeywords
table above had additional columnswhich we’d like to map explicitly, but in most cases we don’trequire direct access to these attributes. Below, we illustratea new mapping which introduces the UserKeyword
class, whichis mapped to the userkeywords
table illustrated earlier.This class adds an additional column special_key
, a value whichwe occasionally want to access, but not in the usual case. Wecreate an association proxy on the User
class calledkeywords
, which will bridge the gap from the user_keywords
collection of User
to the .keyword
attribute present on eachUserKeyword
:
- from sqlalchemy import Column, Integer, String, ForeignKey
- from sqlalchemy.orm import relationship, backref
- from sqlalchemy.ext.associationproxy import association_proxy
- from sqlalchemy.ext.declarative import declarative_base
- Base = declarative_base()
- class User(Base):
- __tablename__ = 'user'
- id = Column(Integer, primary_key=True)
- name = Column(String(64))
- # association proxy of "user_keywords" collection
- # to "keyword" attribute
- keywords = association_proxy('user_keywords', 'keyword')
- def __init__(self, name):
- self.name = name
- class UserKeyword(Base):
- __tablename__ = 'user_keyword'
- user_id = Column(Integer, ForeignKey('user.id'), primary_key=True)
- keyword_id = Column(Integer, ForeignKey('keyword.id'), primary_key=True)
- special_key = Column(String(50))
- # bidirectional attribute/collection of "user"/"user_keywords"
- user = relationship(User,
- backref=backref("user_keywords",
- cascade="all, delete-orphan")
- )
- # reference to the "Keyword" object
- keyword = relationship("Keyword")
- def __init__(self, keyword=None, user=None, special_key=None):
- self.user = user
- self.keyword = keyword
- self.special_key = special_key
- class Keyword(Base):
- __tablename__ = 'keyword'
- id = Column(Integer, primary_key=True)
- keyword = Column('keyword', String(64))
- def __init__(self, keyword):
- self.keyword = keyword
- def __repr__(self):
- 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:
- >>> user = User('log')
- >>> for kw in (Keyword('new_from_blammo'), Keyword('its_big')):
- ... user.keywords.append(kw)
- ...
- >>> print(user.keywords)
- [Keyword('new_from_blammo'), Keyword('its_big')]
Where above, each .keywords.append()
operation is equivalent to:
- >>> 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 passingthe Keyword
object as the first argument. The .user
argument is thenassigned 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, wecreate the UserKeyword
object explicitly. Below we assign all threeattributes, where the assignment of .user
has the effect of the UserKeyword
being appended to the User.user_keywords
collection:
- >>> UserKeyword(Keyword('its_wood'), user, special_key='my special key')
The association proxy returns to us a collection of Keyword
objects representedby all these operations:
- >>> user.keywords
- [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. SQLAlchemymappings usually use the attribute_mapped_collection()
collection type tocreate dictionary collections, as well as the extended techniques described inCustom Dictionary-Based Collections.
The association proxy adjusts its behavior when it detects the usage of adictionary-based collection. When new values are added to the dictionary, theassociation proxy instantiates the intermediary object by passing twoarguments to the creation function instead of one, the key and the value. Asalways, this creation function defaults to the constructor of the intermediaryclass, 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 appropriatelywhen new elements are added to the dictionary:
- from sqlalchemy import Column, Integer, String, ForeignKey
- from sqlalchemy.orm import relationship, backref
- from sqlalchemy.ext.associationproxy import association_proxy
- from sqlalchemy.ext.declarative import declarative_base
- from sqlalchemy.orm.collections import attribute_mapped_collection
- Base = declarative_base()
- class User(Base):
- __tablename__ = 'user'
- id = Column(Integer, primary_key=True)
- name = Column(String(64))
- # proxy to 'user_keywords', instantiating UserKeyword
- # assigning the new key to 'special_key', values to
- # 'keyword'.
- keywords = association_proxy('user_keywords', 'keyword',
- creator=lambda k, v:
- UserKeyword(special_key=k, keyword=v)
- )
- def __init__(self, name):
- self.name = name
- class UserKeyword(Base):
- __tablename__ = 'user_keyword'
- user_id = Column(Integer, ForeignKey('user.id'), primary_key=True)
- keyword_id = Column(Integer, ForeignKey('keyword.id'), primary_key=True)
- special_key = Column(String)
- # bidirectional user/user_keywords relationships, mapping
- # user_keywords with a dictionary against "special_key" as key.
- user = relationship(User, backref=backref(
- "user_keywords",
- collection_class=attribute_mapped_collection("special_key"),
- cascade="all, delete-orphan"
- )
- )
- keyword = relationship("Keyword")
- class Keyword(Base):
- __tablename__ = 'keyword'
- id = Column(Integer, primary_key=True)
- keyword = Column('keyword', String(64))
- def __init__(self, keyword):
- self.keyword = keyword
- def __repr__(self):
- return 'Keyword(%s)' % repr(self.keyword)
We illustrate the .keywords
collection as a dictionary, mapping theUserKeyword.string_key
value to Keyword
objects:
- >>> user = User('log')
- >>> user.keywords['sk1'] = Keyword('kw1')
- >>> user.keywords['sk2'] = Keyword('kw2')
- >>> print(user.keywords)
- {'sk1': Keyword('kw1'), 'sk2': Keyword('kw2')}
Composite Association Proxies
Given our previous examples of proxying from relationship to scalarattribute, 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 valueof special_key
mapped to the string keyword
. Both the UserKeyword
and Keyword
classes are entirely concealed. This is achieved by buildingan association proxy on User
that refers to an association proxypresent on UserKeyword
:
- from sqlalchemy import Column, Integer, String, ForeignKey
- from sqlalchemy.orm import relationship, backref
- from sqlalchemy.ext.associationproxy import association_proxy
- from sqlalchemy.ext.declarative import declarative_base
- from sqlalchemy.orm.collections import attribute_mapped_collection
- Base = declarative_base()
- class User(Base):
- __tablename__ = 'user'
- id = Column(Integer, primary_key=True)
- name = Column(String(64))
- # the same 'user_keywords'->'keyword' proxy as in
- # the basic dictionary example
- keywords = association_proxy(
- 'user_keywords',
- 'keyword',
- creator=lambda k, v:
- UserKeyword(special_key=k, keyword=v)
- )
- def __init__(self, name):
- self.name = name
- class UserKeyword(Base):
- __tablename__ = 'user_keyword'
- user_id = Column(Integer, ForeignKey('user.id'), primary_key=True)
- keyword_id = Column(Integer, ForeignKey('keyword.id'),
- primary_key=True)
- special_key = Column(String)
- user = relationship(User, backref=backref(
- "user_keywords",
- collection_class=attribute_mapped_collection("special_key"),
- cascade="all, delete-orphan"
- )
- )
- # the relationship to Keyword is now called
- # 'kw'
- kw = relationship("Keyword")
- # 'keyword' is changed to be a proxy to the
- # 'keyword' attribute of 'Keyword'
- keyword = association_proxy('kw', 'keyword')
- class Keyword(Base):
- __tablename__ = 'keyword'
- id = Column(Integer, primary_key=True)
- keyword = Column('keyword', String(64))
- def __init__(self, keyword):
- self.keyword = keyword
User.keywords
is now a dictionary of string to string, whereUserKeyword
and Keyword
objects are created and removed for ustransparently using the association proxy. In the example below, we illustrateusage of the assignment operator, also appropriately handled by theassociation proxy, to apply a dictionary value to the collection at once:
- >>> user = User('log')
- >>> user.keywords = {
- ... 'sk1':'kw1',
- ... 'sk2':'kw2'
- ... }
- >>> print(user.keywords)
- {'sk1': 'kw1', 'sk2': 'kw2'}
- >>> user.keywords['sk3'] = 'kw3'
- >>> del user.keywords['sk2']
- >>> print(user.keywords)
- {'sk1': 'kw1', 'sk3': 'kw3'}
- >>> # illustrate un-proxied usage
- ... print(user.user_keywords['sk3'].kw)
- <__main__.Keyword object at 0x12ceb90>
One caveat with our example above is that because Keyword
objects are createdfor each dictionary set operation, the example fails to maintain uniqueness forthe Keyword
objects on their string name, which is a typical requirement fora tagging scenario such as this one. For this use case the recipeUniqueObject, ora comparable creational strategy, isrecommended, which will apply a “lookup first, then create” strategy to the constructorof the Keyword
class, so that an already existing Keyword
is returned if thegiven name is already present.
Querying with Association Proxies
The AssociationProxy
features simple SQL construction capabilitieswhich relate down to the underlying relationship()
in use as wellas the target attribute. For example, the RelationshipProperty.Comparator.any()
and RelationshipProperty.Comparator.has()
operations are available, and will producea “nested” EXISTS clause, such as in our basic association object example:
- >>> print(session.query(User).filter(User.keywords.any(keyword='jek')))
- SELECT user.id AS user_id, user.name AS user_name
- FROM user
- WHERE EXISTS (SELECT 1
- FROM user_keyword
- WHERE user.id = user_keyword.user_id AND (EXISTS (SELECT 1
- FROM keyword
- WHERE keyword.id = user_keyword.keyword_id AND keyword.keyword = :keyword_1)))
For a proxy to a scalar attribute, eq()
is supported:
- >>> print(session.query(UserKeyword).filter(UserKeyword.keyword == 'jek'))
- SELECT user_keyword.*
- FROM user_keyword
- WHERE EXISTS (SELECT 1
- FROM keyword
- WHERE keyword.id = user_keyword.keyword_id AND keyword.keyword = :keyword_1)
and .contains()
is available for a proxy to a scalar collection:
- >>> print(session.query(User).filter(User.keywords.contains('jek')))
- SELECT user.*
- FROM user
- WHERE EXISTS (SELECT 1
- FROM userkeywords, keyword
- WHERE user.id = userkeywords.user_id
- AND keyword.id = userkeywords.keyword_id
- AND keyword.keyword = :keyword_1)
AssociationProxy
can be used with Query.join()
somewhat manuallyusing the attr
attribute in a star-args context:
- q = session.query(User).join(*User.keywords.attr)
attr
is composed of AssociationProxy.local_attr
and AssociationProxy.remote_attr
,which are just synonyms for the actual proxied attributes, and can alsobe used for querying:
- uka = aliased(UserKeyword)
- ka = aliased(Keyword)
- q = session.query(User).\
- join(uka, User.keywords.local_attr).\
- join(ka, User.keywords.remote_attr)
Cascading Scalar Deletes
New in version 1.3.
Given a mapping as:
- class A(Base):
- __tablename__ = 'test_a'
- id = Column(Integer, primary_key=True)
- ab = relationship(
- 'AB', backref='a', uselist=False)
- b = association_proxy(
- 'ab', 'b', creator=lambda b: AB(b=b),
- cascade_scalar_deletes=True)
- class B(Base):
- __tablename__ = 'test_b'
- id = Column(Integer, primary_key=True)
- ab = relationship('AB', backref='b', cascade='all, delete-orphan')
- class AB(Base):
- __tablename__ = 'test_ab'
- a_id = Column(Integer, ForeignKey(A.id), primary_key=True)
- b_id = Column(Integer, ForeignKey(B.id), primary_key=True)
An assignment to A.b
will generate an AB
object:
- a.b = B()
The A.b
association is scalar, and includes use of the flagAssociationProxy.cascade_scalar_deletes
. When set, setting A.b
to None
will remove A.ab
as well:
- a.b = None
- 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 whenmembers of the proxied collection are removed. Whether or not the row isdeleted depends on the relationship cascade setting.
See also
API Documentation
sqlalchemy.ext.associationproxy.
associationproxy
(_target_collection, attr, **kw)- Return a Python property implementing a view of a targetattribute which references an attribute on members of thetarget.
The returned value is an instance of AssociationProxy
.
Implements a Python property representing a relationship as a collectionof simpler values, or a scalar value. The proxied property will mimicthe collection type of the target (list, dict or set), or, in the case ofa 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, butcan also be a many-to-one or non-scalar relationship.
Attribute on the associated instance or instances we’llproxy for.
For example, given a target collection of [obj1, obj2], a list createdby this proxy property would look like [getattr(obj1, attr),getattr(obj2, attr)]
If the relationship is one-to-one or otherwise uselist=False, thensimply: getattr(obj, attr)
-
optional.
When new items are added to this proxied collection, new instances ofthe class collected by the target collection will be created. For listand set collections, the target class constructor will be called withthe ‘value’ for the new instance. For dict types, two arguments arepassed: 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 theassociated object.
If you have an associated object with multiple attributes, you may setup multiple association proxies mapping to different attributes. Seethe unit tests for examples, and for examples of how creator() functionscan be used to construct the scalar relationship on-demand in thissituation.
-
**kw – Passes along any other keyword arguments toAssociationProxy
.
- 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) - Bases:
sqlalchemy.orm.base.InspectionAttrInfo
A descriptor that presents a read/write view of an object attribute.
inherited from the eq()
method of object
Return self==value.
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 usualentrypoint here, though AssociationProxy
can be instantiatedand/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 proxyfor. For example, given a target collection of [obj1, obj2], alist created by this proxy property would look like[getattr(obj1, attr), getattr(obj2, attr)]
-
Optional. When new items are added to this proxiedcollection, new instances of the class collected by the targetcollection will be created. For list and set collections, thetarget class constructor will be called with the ‘value’ for thenew 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.
-
when True, indicates that settingthe proxied value to None
, or deleting it via del
, shouldalso remove the source object. Only applies to scalar attributes.Normally, removing the proxied target will not remove the proxysource, as this object may have other state that is still to bekept.
New in version 1.3.
See also
Cascading Scalar Deletes - complete usage example
-
Optional. Proxied attribute access isautomatically handled by routines that get and set values based onthe attr argument for this proxy.
If you would like to customize this behavior, you may supply agetset_factory callable that produces a tuple of getter andsetter functions. The factory is called with two arguments, theabstract type of the underlying collection and this proxy instance.
-
proxy_factory – Optional. The type of collection to emulate isdetermined by sniffing the target collection. If your collectiontype can’t be determined by duck typing or you’d like to use adifferent collection implementation, you may supply a factoryfunction to produce those collections. Only applicable tonon-scalar relationships.
-
proxy_bulk_set – Optional, use with proxy_factory. Seethe _set() method for details.
-
optional, will be assigned toAssociationProxy.info
if present.
New in version 1.0.9.
inherited from the le()
method of object
Return self<=value.
inherited from the lt()
method of object
Return self
- 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 invokedin terms of a specific class or instance of a class, i.e. when it isused as a regular Python descriptor.
When referring to the AssociationProxy
as a normal Pythondescriptor, the AssociationProxyInstance
is the object thatactually serves the information. Under normal circumstances, its presenceis transparent:
- >>> User.keywords.scalar
- False
In the special case that the AssociationProxy
object is beingaccessed directly, in order to get an explicit handle to theAssociationProxyInstance
, use theAssociationProxy.for_class()
method:
- proxy_state = inspect(User).all_orm_descriptors["keywords"].for_class(User)
- # view if proxy object is scalar or not
- >>> proxy_state.scalar
- False
New in version 1.3.
inherited from the eq()
method of object
Return self==value.
inherited from the le()
method of object
Return self<=value.
inherited from the lt()
method of object
Return self
- class
sqlalchemy.ext.associationproxy.
ObjectAssociationProxyInstance
(parent, owning_class, target_class, value_attr) - Bases:
sqlalchemy.ext.associationproxy.AssociationProxyInstance
an AssociationProxyInstance
that has an object as a target.
inherited from the le()
method of object
Return self<=value.
inherited from the lt()
method of object
Return self
- class
sqlalchemy.ext.associationproxy.
ColumnAssociationProxyInstance
(parent, owning_class, target_class, value_attr) - Bases:
sqlalchemy.sql.operators.ColumnOperators
,sqlalchemy.ext.associationproxy.AssociationProxyInstance
an AssociationProxyInstance
that has a database column as atarget.
inherited from thele()
method ofColumnOperators
Implement the <=
operator.
In a column context, produces the clause a <= b
.
inherited from thelt()
method ofColumnOperators
Implement the <
operator.
In a column context, produces the clause a < b
.
inherited from thene()
method ofColumnOperators
Implement the !=
operator.
In a column context, produces the clause a != b
.If the target is None
, produces a IS NOT NULL
.
inherited from theall_()
method ofColumnOperators
Produce a all_()
clause against theparent object.
This operator is only appropriate against a scalar subqueryobject, or for some backends an column expression that isagainst the ARRAY type, e.g.:
- # postgresql '5 = ALL (somearray)'
- expr = 5 == mytable.c.somearray.all_()
- # mysql '5 = ALL (SELECT value FROM table)'
- expr = 5 == select([table.c.value]).as_scalar().all_()
See also
all_()
- standalone version
any_()
- ANY operator
New in version 1.1.
inherited from theany()
method ofAssociationProxyInstance
Produce a proxied ‘any’ expression using EXISTS.
This expression will be a composed productusing the RelationshipProperty.Comparator.any()
and/or RelationshipProperty.Comparator.has()
operators of the underlying proxied attributes.
inherited from theany_()
method ofColumnOperators
Produce a any_()
clause against theparent object.
This operator is only appropriate against a scalar subqueryobject, or for some backends an column expression that isagainst the ARRAY type, e.g.:
- # postgresql '5 = ANY (somearray)'
- expr = 5 == mytable.c.somearray.any_()
- # mysql '5 = ANY (SELECT value FROM table)'
- expr = 5 == select([table.c.value]).as_scalar().any_()
See also
any_()
- standalone version
all_()
- ALL operator
New in version 1.1.
inherited from theasc()
method ofColumnOperators
Produce a asc()
clause against theparent object.
This attribute is convenient when specifying a joinusing Query.join()
across two relationships:
- sess.query(Parent).join(*Parent.proxied.attr)
See also
AssociationProxyInstance.local_attr
AssociationProxyInstance.remote_attr
inherited from thebetween()
method ofColumnOperators
Produce a between()
clause againstthe parent object, given the lower and upper range.
inherited from thebool_op()
method ofOperators
Return a custom boolean operator.
This method is shorthand for callingOperators.op()
and passing theOperators.op.is_comparison
flag with True.
New in version 1.2.0b3.
See also
inherited from thecollate()
method ofColumnOperators
Produce a collate()
clause againstthe parent object, given the collation string.
See also
inherited from theconcat()
method ofColumnOperators
Implement the ‘concat’ operator.
In a column context, produces the clause a || b
,or uses the concat()
operator on MySQL.
inherited from thecontains()
method ofColumnOperators
Implement the ‘contains’ operator.
Produces a LIKE expression that tests against a match for the middleof a string value:
- column LIKE '%' || <other> || '%'
E.g.:
- stmt = select([sometable]).\
- where(sometable.c.column.contains("foobar"))
Since the operator uses LIKE
, wildcard characters"%"
and "_"
that are present inside the ColumnOperators.contains.autoescape
flagmay be set to True
to apply escaping to occurrences of thesecharacters within the string value so that they match as themselvesand not as wildcard characters. Alternatively, theColumnOperators.contains.escape
parameter will establisha given character as an escape character which can be of use whenthe target expression is not a literal string.
- Parameters
-
-
other – expression to be compared. This is usually a plainstring value, but can also be an arbitrary SQL expression. LIKEwildcard characters %
and _
are not escaped by default unlessthe ColumnOperators.contains.autoescape
flag isset to True.
-
boolean; when True, establishes an escape characterwithin the LIKE expression, then applies it to all occurrences of"%"
, "_"
and the escape character itself within thecomparison value, which is assumed to be a literal string and not aSQL expression.
An expression such as:
- somecolumn.contains("foo%bar", autoescape=True)
Will render as:
- somecolumn LIKE '%' || :param || '%' ESCAPE '/'
With the value of :param as "foo/%bar"
.
New in version 1.2.
Changed in version 1.2.0: TheColumnOperators.contains.autoescape
parameter is now a simple boolean rather than a character; the escape character itself is also escaped, and defaults to a forwards slash, which itself can be customized using the ColumnOperators.contains.escape
parameter.
-
a character which when given will render with theESCAPE
keyword to establish that character as the escapecharacter. This character can then be placed preceding occurrencesof %
and _
to allow them to act as themselves and notwildcard characters.
An expression such as:
- somecolumn.contains("foo/%bar", escape="^")
Will render as:
- somecolumn LIKE '%' || :param || '%' ESCAPE '^'
The parameter may also be combined withColumnOperators.contains.autoescape
:
- somecolumn.contains("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.
See also
inherited from thedesc()
method ofColumnOperators
Produce a desc()
clause against theparent object.
inherited from thedistinct()
method ofColumnOperators
Produce a distinct()
clause against theparent object.
inherited from theendswith()
method ofColumnOperators
Implement the ‘endswith’ operator.
Produces a LIKE expression that tests against a match for the endof a string value:
- column LIKE '%' || <other>
E.g.:
- stmt = select([sometable]).\
- where(sometable.c.column.endswith("foobar"))
Since the operator uses LIKE
, wildcard characters"%"
and "_"
that are present inside the ColumnOperators.endswith.autoescape
flagmay be set to True
to apply escaping to occurrences of thesecharacters within the string value so that they match as themselvesand not as wildcard characters. Alternatively, theColumnOperators.endswith.escape
parameter will establisha given character as an escape character which can be of use whenthe target expression is not a literal string.
- Parameters
-
-
other – expression to be compared. This is usually a plainstring value, but can also be an arbitrary SQL expression. LIKEwildcard characters %
and _
are not escaped by default unlessthe ColumnOperators.endswith.autoescape
flag isset to True.
-
boolean; when True, establishes an escape characterwithin the LIKE expression, then applies it to all occurrences of"%"
, "_"
and the escape character itself within thecomparison value, which is assumed to be a literal string and not aSQL expression.
An expression such as:
- somecolumn.endswith("foo%bar", autoescape=True)
Will render as:
- somecolumn LIKE '%' || :param ESCAPE '/'
With the value of :param as "foo/%bar"
.
New in version 1.2.
Changed in version 1.2.0: TheColumnOperators.endswith.autoescape
parameter is now a simple boolean rather than a character; the escape character itself is also escaped, and defaults to a forwards slash, which itself can be customized using the ColumnOperators.endswith.escape
parameter.
-
a character which when given will render with theESCAPE
keyword to establish that character as the escapecharacter. This character can then be placed preceding occurrencesof %
and _
to allow them to act as themselves and notwildcard characters.
An expression such as:
- somecolumn.endswith("foo/%bar", escape="^")
Will render as:
- somecolumn LIKE '%' || :param ESCAPE '^'
The parameter may also be combined withColumnOperators.endswith.autoescape
:
- 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.
See also
inherited from thehas()
method ofAssociationProxyInstance
Produce a proxied ‘has’ expression using EXISTS.
This expression will be a composed productusing the RelationshipProperty.Comparator.any()
and/or RelationshipProperty.Comparator.has()
operators of the underlying proxied attributes.
inherited from theilike()
method ofColumnOperators
Implement the ilike
operator, e.g. case insensitive LIKE.
In a column context, produces an expression either of the form:
- lower(a) LIKE lower(other)
Or on backends that support the ILIKE operator:
- a ILIKE other
E.g.:
- stmt = select([sometable]).\
- where(sometable.c.column.ilike("%foobar%"))
- Parameters
-
-
other – expression to be compared
-
optional escape character, renders the ESCAPE
keyword, e.g.:
- somecolumn.ilike("foo/%bar", escape="/")
See also
inherited from thein_()
method ofColumnOperators
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.:
- stmt.where(column.in_([1, 2, 3]))
In this calling form, the list of items is converted to a set ofbound parameters the same length as the list given:
- WHERE COL IN (?, ?, ?)
-
A list of tuples may be provided if the comparison is against atuple_()
containing multiple expressions:
- from sqlalchemy import tuple_
- stmt.where(tuple_(col1, col2).in_([(1, 10), (2, 20), (3, 30)]))
-
An empty list, e.g.:
- stmt.where(column.in_([]))
In this calling form, the expression renders a “false” expression,e.g.:
- WHERE 1 != 1
This “false” expression has historically had different behaviorsin older SQLAlchemy versions, seecreate_engine.empty_in_strategy
for behavioral options.
Changed in version 1.2: simplified the behavior of “empty in”expressions
-
A bound parameter, e.g. bindparam()
, may be used if itincludes the bindparam.expanding
flag:
- stmt.where(column.in_(bindparam('value', expanding=True)))
In this calling form, the expression renders a special non-SQLplaceholder expression that looks like:
- WHERE COL IN ([EXPANDING_value])
This placeholder expression is intercepted at statement executiontime to be converted into the variable number of bound parameterform illustrated earlier. If the statement were executed as:
- connection.execute(stmt, {"value": [1, 2, 3]})
The database would be passed a bound parameter for each value:
- 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. OnSQLite this would be:
- WHERE COL IN (SELECT 1 FROM (SELECT 1) WHERE 1!=1)
New in version 1.3: “expanding” bound parameters now supportempty lists
-
a select()
construct, which is usually a correlatedscalar select:
- stmt.where(
- column.in_(
- select([othertable.c.y]).
- where(table.c.x == othertable.c.x)
- )
- )
In this calling form, ColumnOperators.in_()
renders as given:
- WHERE COL IN (SELECT othertable.y
- FROM othertable WHERE othertable.x = table.x)
- Parameters
-
other – a list of literals, a select()
construct,or a bindparam()
construct that includes thebindparam.expanding
flag set to True.
inherited from theis_()
method ofColumnOperators
Implement the IS
operator.
Normally, IS
is generated automatically when comparing to avalue of None
, which resolves to NULL
. However, explicitusage of IS
may be desirable if comparing to boolean valueson certain platforms.
See also
inherited from theis_distinct_from()
method ofColumnOperators
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.
inherited from theisnot()
method ofColumnOperators
Implement the IS NOT
operator.
Normally, IS NOT
is generated automatically when comparing to avalue of None
, which resolves to NULL
. However, explicitusage of IS NOT
may be desirable if comparing to boolean valueson certain platforms.
See also
inherited from theisnot_distinct_from()
method ofColumnOperators
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”.
New in version 1.1.
inherited from thelike()
method ofColumnOperators
Implement the like
operator.
In a column context, produces the expression:
- a LIKE other
E.g.:
- stmt = select([sometable]).\
- where(sometable.c.column.like("%foobar%"))
- Parameters
-
-
other – expression to be compared
-
optional escape character, renders the ESCAPE
keyword, e.g.:
- somecolumn.like("foo/%bar", escape="/")
See also
- property
local_attr
- The ‘local’ class attribute referenced by this
AssociationProxyInstance
.
See also
AssociationProxyInstance.attr
AssociationProxyInstance.remote_attr
inherited from thematch()
method ofColumnOperators
Implements a database-specific ‘match’ operator.
match()
attempts to resolve toa MATCH-like function or operator provided by the backend.Examples include:
-
PostgreSQL - renders x @@ to_tsquery(y)
-
MySQL - renders MATCH (x) AGAINST (y IN BOOLEAN MODE)
-
Oracle - renders CONTAINS(x, y)
-
other backends may provide special implementations.
-
Backends without any special implementation will emitthe operator as “MATCH”. This is compatible with SQLite, forexample.
inherited from thenotilike()
method ofColumnOperators
implement the NOT ILIKE
operator.
This is equivalent to using negation withColumnOperators.ilike()
, i.e. ~x.ilike(y)
.
See also
inherited from thenotin_()
method ofColumnOperators
implement the NOT IN
operator.
This is equivalent to using negation withColumnOperators.in_()
, i.e. ~x.in_(y)
.
In the case that other
is an empty sequence, the compilerproduces an “empty not in” expression. This defaults to theexpression “1 = 1” to produce true in all cases. Thecreate_engine.empty_in_strategy
may be used toalter this behavior.
Changed in version 1.2: The ColumnOperators.in_()
andColumnOperators.notin_()
operatorsnow produce a “static” expression for an empty IN sequenceby default.
See also
inherited from thenotlike()
method ofColumnOperators
implement the NOT LIKE
operator.
This is equivalent to using negation withColumnOperators.like()
, i.e. ~x.like(y)
.
See also
inherited from thenullsfirst()
method ofColumnOperators
Produce a nullsfirst()
clause against theparent object.
inherited from thenullslast()
method ofColumnOperators
Produce a nullslast()
clause against theparent object.
inherited from theop()
method ofOperators
produce a generic operator function.
e.g.:
- somecolumn.op("*")(5)
produces:
- somecolumn * 5
This function can also be used to make bitwise operators explicit. Forexample:
- somecolumn.op('&')(0xff)
is a bitwise AND of the value in somecolumn
.
- Parameters
-
-
operator – a string which will be output as the infix operatorbetween this element and the expression passed to thegenerated function.
-
precedence – precedence to apply to the operator, whenparenthesizing expressions. A lower number will cause the expressionto be parenthesized when applied against another operator withhigher precedence. The default value of 0
is lower than alloperators except for the comma (,
) and AS
operators.A value of 100 will be higher or equal to all operators, and -100will be lower than or equal to all operators.
-
if True, the operator will be considered as a“comparison” operator, that is which evaluates to a booleantrue/false value, like ==
, >
, etc. This flag should be setso that ORM relationships can establish that the operator is acomparison operator when used in a custom join condition.
New in version 0.9.2: - added theOperators.op.is_comparison
flag.
-
a TypeEngine
class or object that willforce the return type of an expression produced by this operatorto be of that type. By default, operators that specifyOperators.op.is_comparison
will resolve toBoolean
, and those that do not will be of the sametype as the left-hand operand.
New in version 1.2.0b3: - added theOperators.op.return_type
argument.
See also
Redefining and Creating New Operators
Using custom operators in join conditions
This is the lowest level of operation, raisesNotImplementedError
by default.
Overriding this on a subclass can allow commonbehavior to be applied to all operations.For example, overriding ColumnOperators
to apply func.lower()
to the left and rightside:
- class MyComparator(ColumnOperators):
- def operate(self, op, other):
- return op(func.lower(self), func.lower(other))
- Parameters
-
-
-
*other – the ‘other’ side of the operation. Willbe a single scalar for most operations.
-
**kwargs – modifiers. These may be passed by specialoperators such as ColumnOperators.contains()
.
- property
remote_attr
- The ‘remote’ class attribute referenced by this
AssociationProxyInstance
.
See also
AssociationProxyInstance.attr
AssociationProxyInstance.local_attr
inherited from thereverse_operate()
method ofOperators
Reverse operate on an argument.
Usage is the same as operate()
.
inherited from thescalar
attribute ofAssociationProxyInstance
Return True
if this AssociationProxyInstance
proxies a scalar relationship on the local side.
inherited from thestartswith()
method ofColumnOperators
Implement the startswith
operator.
Produces a LIKE expression that tests against a match for the startof a string value:
- column LIKE <other> || '%'
E.g.:
- stmt = select([sometable]).\
- where(sometable.c.column.startswith("foobar"))
Since the operator uses LIKE
, wildcard characters"%"
and "_"
that are present inside the ColumnOperators.startswith.autoescape
flagmay be set to True
to apply escaping to occurrences of thesecharacters within the string value so that they match as themselvesand not as wildcard characters. Alternatively, theColumnOperators.startswith.escape
parameter will establisha given character as an escape character which can be of use whenthe target expression is not a literal string.
- Parameters
-
-
other – expression to be compared. This is usually a plainstring value, but can also be an arbitrary SQL expression. LIKEwildcard characters %
and _
are not escaped by default unlessthe ColumnOperators.startswith.autoescape
flag isset to True.
-
boolean; when True, establishes an escape characterwithin the LIKE expression, then applies it to all occurrences of"%"
, "_"
and the escape character itself within thecomparison value, which is assumed to be a literal string and not aSQL expression.
An expression such as:
- somecolumn.startswith("foo%bar", autoescape=True)
Will render as:
- somecolumn LIKE :param || '%' ESCAPE '/'
With the value of :param as "foo/%bar"
.
New in version 1.2.
Changed in version 1.2.0: TheColumnOperators.startswith.autoescape
parameter is now a simple boolean rather than a character; the escape character itself is also escaped, and defaults to a forwards slash, which itself can be customized using the ColumnOperators.startswith.escape
parameter.
-
a character which when given will render with theESCAPE
keyword to establish that character as the escapecharacter. This character can then be placed preceding occurrencesof %
and _
to allow them to act as themselves and notwildcard characters.
An expression such as:
- somecolumn.startswith("foo/%bar", escape="^")
Will render as:
- somecolumn LIKE :param || '%' ESCAPE '^'
The parameter may also be combined withColumnOperators.startswith.autoescape
:
- somecolumn.startswith("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.
See also
sqlalchemy.ext.associationproxy.
ASSOCIATIONPROXY
= symbol('ASSOCIATIONPROXY')- Symbol indicating an
InspectionAttr
that’s - of type
AssociationProxy
.
- Symbol indicating an
Is assigned to the InspectionAttr.extension_type
attribute.