Hybrid Attributes
Define attributes on ORM-mapped classes that have “hybrid” behavior.
“hybrid” means the attribute has distinct behaviors defined at theclass level and at the instance level.
The hybrid
extension provides a special form ofmethod decorator, is around 50 lines of code and has almost nodependencies on the rest of SQLAlchemy. It can, in theory, work withany descriptor-based expression system.
Consider a mapping Interval
, representing integer start
and end
values. We can define higher level functions on mapped classes that produce SQLexpressions at the class level, and Python expression evaluation at theinstance level. Below, each function decorated with hybrid_method
orhybrid_property
may receive self
as an instance of the class, oras the class itself:
- from sqlalchemy import Column, Integer
- from sqlalchemy.ext.declarative import declarative_base
- from sqlalchemy.orm import Session, aliased
- from sqlalchemy.ext.hybrid import hybrid_property, hybrid_method
- Base = declarative_base()
- class Interval(Base):
- __tablename__ = 'interval'
- id = Column(Integer, primary_key=True)
- start = Column(Integer, nullable=False)
- end = Column(Integer, nullable=False)
- def __init__(self, start, end):
- self.start = start
- self.end = end
- @hybrid_property
- def length(self):
- return self.end - self.start
- @hybrid_method
- def contains(self, point):
- return (self.start <= point) & (point <= self.end)
- @hybrid_method
- def intersects(self, other):
- return self.contains(other.start) | self.contains(other.end)
Above, the length
property returns the difference between theend
and start
attributes. With an instance of Interval
,this subtraction occurs in Python, using normal Python descriptormechanics:
- >>> i1 = Interval(5, 10)
- >>> i1.length
- 5
When dealing with the Interval
class itself, the hybrid_property
descriptor evaluates the function body given the Interval
class asthe argument, which when evaluated with SQLAlchemy expression mechanicsreturns a new SQL expression:
- >>> print Interval.length
- interval."end" - interval.start
- >>> print Session().query(Interval).filter(Interval.length > 10)
- SELECT interval.id AS interval_id, interval.start AS interval_start,
- interval."end" AS interval_end
- FROM interval
- WHERE interval."end" - interval.start > :param_1
ORM methods such as filter_by()
generally use getattr()
tolocate attributes, so can also be used with hybrid attributes:
- >>> print Session().query(Interval).filter_by(length=5)
- SELECT interval.id AS interval_id, interval.start AS interval_start,
- interval."end" AS interval_end
- FROM interval
- WHERE interval."end" - interval.start = :param_1
The Interval
class example also illustrates two methods,contains()
and intersects()
, decorated withhybrid_method
. This decorator applies the same idea tomethods that hybrid_property
applies to attributes. Themethods return boolean values, and take advantage of the Python |
and &
bitwise operators to produce equivalent instance-level andSQL expression-level boolean behavior:
- >>> i1.contains(6)
- True
- >>> i1.contains(15)
- False
- >>> i1.intersects(Interval(7, 18))
- True
- >>> i1.intersects(Interval(25, 29))
- False
- >>> print Session().query(Interval).filter(Interval.contains(15))
- SELECT interval.id AS interval_id, interval.start AS interval_start,
- interval."end" AS interval_end
- FROM interval
- WHERE interval.start <= :start_1 AND interval."end" > :end_1
- >>> ia = aliased(Interval)
- >>> print Session().query(Interval, ia).filter(Interval.intersects(ia))
- SELECT interval.id AS interval_id, interval.start AS interval_start,
- interval."end" AS interval_end, interval_1.id AS interval_1_id,
- interval_1.start AS interval_1_start, interval_1."end" AS interval_1_end
- FROM interval, interval AS interval_1
- WHERE interval.start <= interval_1.start
- AND interval."end" > interval_1.start
- OR interval.start <= interval_1."end"
- AND interval."end" > interval_1."end"
Defining Expression Behavior Distinct from Attribute Behavior
Our usage of the &
and |
bitwise operators above wasfortunate, considering our functions operated on two boolean values toreturn a new one. In many cases, the construction of an in-Pythonfunction and a SQLAlchemy SQL expression have enough differences thattwo separate Python expressions should be defined. Thehybrid
decorators define thehybrid_property.expression()
modifier for this purpose. As anexample we’ll define the radius of the interval, which requires theusage of the absolute value function:
- from sqlalchemy import func
- class Interval(object):
- # ...
- @hybrid_property
- def radius(self):
- return abs(self.length) / 2
- @radius.expression
- def radius(cls):
- return func.abs(cls.length) / 2
Above the Python function abs()
is used for instance-leveloperations, the SQL function ABS()
is used via the func
object for class-level expressions:
- >>> i1.radius
- 2
- >>> print Session().query(Interval).filter(Interval.radius > 5)
- SELECT interval.id AS interval_id, interval.start AS interval_start,
- interval."end" AS interval_end
- FROM interval
- WHERE abs(interval."end" - interval.start) / :abs_1 > :param_1
Note
When defining an expression for a hybrid property or method, theexpression method must retain the name of the original hybrid, elsethe new hybrid with the additional state will be attached to the classwith the non-matching name. To use the example above:
- class Interval(object):
- # ...
- @hybrid_property
- def radius(self):
- return abs(self.length) / 2
- # WRONG - the non-matching name will cause this function to be
- # ignored
- @radius.expression
- def radius_expression(cls):
- return func.abs(cls.length) / 2
This is also true for other mutator methods, such ashybrid_property.update_expression()
. This is the same behavioras that of the @property
construct that is part of standard Python.
Defining Setters
Hybrid properties can also define setter methods. If we wantedlength
above, when set, to modify the endpoint value:
- class Interval(object):
- # ...
- @hybrid_property
- def length(self):
- return self.end - self.start
- @length.setter
- def length(self, value):
- self.end = self.start + value
The length(self, value)
method is now called upon set:
- >>> i1 = Interval(5, 10)
- >>> i1.length
- 5
- >>> i1.length = 12
- >>> i1.end
- 17
Allowing Bulk ORM Update
A hybrid can define a custom “UPDATE” handler for when using theQuery.update()
method, allowing the hybrid to be used in theSET clause of the update.
Normally, when using a hybrid with Query.update()
, the SQLexpression is used as the column that’s the target of the SET. If ourInterval
class had a hybrid start_point
that linked toInterval.start
, this could be substituted directly:
- session.query(Interval).update({Interval.start_point: 10})
However, when using a composite hybrid like Interval.length
, thishybrid represents more than one column. We can set up a handler that willaccommodate a value passed to Query.update()
which can affectthis, using the hybrid_property.update_expression()
decorator.A handler that works similarly to our setter would be:
- class Interval(object):
- # ...
- @hybrid_property
- def length(self):
- return self.end - self.start
- @length.setter
- def length(self, value):
- self.end = self.start + value
- @length.update_expression
- def length(cls, value):
- return [
- (cls.end, cls.start + value)
- ]
Above, if we use Interval.length
in an UPDATE expression as:
- session.query(Interval).update(
- {Interval.length: 25}, synchronize_session='fetch')
We’ll get an UPDATE statement along the lines of:
- UPDATE interval SET end=start + :value
In some cases, the default “evaluate” strategy can’t perform the SETexpression in Python; while the addition operator we’re using aboveis supported, for more complex SET expressions it will usually be necessaryto use either the “fetch” or False synchronization strategy as illustratedabove.
New in version 1.2: added support for bulk updates to hybrid properties.
Working with Relationships
There’s no essential difference when creating hybrids that work withrelated objects as opposed to column-based data. The need for distinctexpressions tends to be greater. The two variants we’ll illustrateare the “join-dependent” hybrid, and the “correlated subquery” hybrid.
Join-Dependent Relationship Hybrid
Consider the following declarativemapping which relates a User
to a SavingsAccount
:
- from sqlalchemy import Column, Integer, ForeignKey, Numeric, String
- from sqlalchemy.orm import relationship
- from sqlalchemy.ext.declarative import declarative_base
- from sqlalchemy.ext.hybrid import hybrid_property
- Base = declarative_base()
- class SavingsAccount(Base):
- __tablename__ = 'account'
- id = Column(Integer, primary_key=True)
- user_id = Column(Integer, ForeignKey('user.id'), nullable=False)
- balance = Column(Numeric(15, 5))
- class User(Base):
- __tablename__ = 'user'
- id = Column(Integer, primary_key=True)
- name = Column(String(100), nullable=False)
- accounts = relationship("SavingsAccount", backref="owner")
- @hybrid_property
- def balance(self):
- if self.accounts:
- return self.accounts[0].balance
- else:
- return None
- @balance.setter
- def balance(self, value):
- if not self.accounts:
- account = Account(owner=self)
- else:
- account = self.accounts[0]
- account.balance = value
- @balance.expression
- def balance(cls):
- return SavingsAccount.balance
The above hybrid property balance
works with the firstSavingsAccount
entry in the list of accounts for this user. Thein-Python getter/setter methods can treat accounts
as a Pythonlist available on self
.
However, at the expression level, it’s expected that the User
class willbe used in an appropriate context such that an appropriate join toSavingsAccount
will be present:
- >>> print Session().query(User, User.balance).\
- ... join(User.accounts).filter(User.balance > 5000)
- SELECT "user".id AS user_id, "user".name AS user_name,
- account.balance AS account_balance
- FROM "user" JOIN account ON "user".id = account.user_id
- WHERE account.balance > :balance_1
Note however, that while the instance level accessors need to worryabout whether self.accounts
is even present, this issue expressesitself differently at the SQL expression level, where we basicallywould use an outer join:
- >>> from sqlalchemy import or_
- >>> print (Session().query(User, User.balance).outerjoin(User.accounts).
- ... filter(or_(User.balance < 5000, User.balance == None)))
- SELECT "user".id AS user_id, "user".name AS user_name,
- account.balance AS account_balance
- FROM "user" LEFT OUTER JOIN account ON "user".id = account.user_id
- WHERE account.balance < :balance_1 OR account.balance IS NULL
Correlated Subquery Relationship Hybrid
We can, of course, forego being dependent on the enclosing query’s usageof joins in favor of the correlated subquery, which can portably be packedinto a single column expression. A correlated subquery is more portable, butoften performs more poorly at the SQL level. Using the same techniqueillustrated at Using column_property,we can adjust our SavingsAccount
example to aggregate the balances forall accounts, and use a correlated subquery for the column expression:
- from sqlalchemy import Column, Integer, ForeignKey, Numeric, String
- from sqlalchemy.orm import relationship
- from sqlalchemy.ext.declarative import declarative_base
- from sqlalchemy.ext.hybrid import hybrid_property
- from sqlalchemy import select, func
- Base = declarative_base()
- class SavingsAccount(Base):
- __tablename__ = 'account'
- id = Column(Integer, primary_key=True)
- user_id = Column(Integer, ForeignKey('user.id'), nullable=False)
- balance = Column(Numeric(15, 5))
- class User(Base):
- __tablename__ = 'user'
- id = Column(Integer, primary_key=True)
- name = Column(String(100), nullable=False)
- accounts = relationship("SavingsAccount", backref="owner")
- @hybrid_property
- def balance(self):
- return sum(acc.balance for acc in self.accounts)
- @balance.expression
- def balance(cls):
- return select([func.sum(SavingsAccount.balance)]).\
- where(SavingsAccount.user_id==cls.id).\
- label('total_balance')
The above recipe will give us the balance
column which rendersa correlated SELECT:
- >>> print s.query(User).filter(User.balance > 400)
- SELECT "user".id AS user_id, "user".name AS user_name
- FROM "user"
- WHERE (SELECT sum(account.balance) AS sum_1
- FROM account
- WHERE account.user_id = "user".id) > :param_1
Building Custom Comparators
The hybrid property also includes a helper that allows construction ofcustom comparators. A comparator object allows one to customize thebehavior of each SQLAlchemy expression operator individually. Theyare useful when creating custom types that have some highlyidiosyncratic behavior on the SQL side.
Note
The hybrid_property.comparator()
decorator introducedin this section replaces the use of thehybrid_property.expression()
decorator.They cannot be used together.
The example class below allows case-insensitive comparisons on the attributenamed word_insensitive
:
- from sqlalchemy.ext.hybrid import Comparator, hybrid_property
- from sqlalchemy import func, Column, Integer, String
- from sqlalchemy.orm import Session
- from sqlalchemy.ext.declarative import declarative_base
- Base = declarative_base()
- class CaseInsensitiveComparator(Comparator):
- def __eq__(self, other):
- return func.lower(self.__clause_element__()) == func.lower(other)
- class SearchWord(Base):
- __tablename__ = 'searchword'
- id = Column(Integer, primary_key=True)
- word = Column(String(255), nullable=False)
- @hybrid_property
- def word_insensitive(self):
- return self.word.lower()
- @word_insensitive.comparator
- def word_insensitive(cls):
- return CaseInsensitiveComparator(cls.word)
Above, SQL expressions against word_insensitive
will apply the LOWER()
SQL function to both sides:
- >>> print Session().query(SearchWord).filter_by(word_insensitive="Trucks")
- SELECT searchword.id AS searchword_id, searchword.word AS searchword_word
- FROM searchword
- WHERE lower(searchword.word) = lower(:lower_1)
The CaseInsensitiveComparator
above implements part of theColumnOperators
interface. A “coercion” operation likelowercasing can be applied to all comparison operations (i.e. eq
,lt
, gt
, etc.) using Operators.operate()
:
- class CaseInsensitiveComparator(Comparator):
- def operate(self, op, other):
- return op(func.lower(self.__clause_element__()), func.lower(other))
Reusing Hybrid Properties across Subclasses
A hybrid can be referred to from a superclass, to allow modifyingmethods like hybrid_property.getter()
, hybrid_property.setter()
to be used to redefine those methods on a subclass. This is similar tohow the standard Python @property
object works:
- class FirstNameOnly(Base):
- # ...
- first_name = Column(String)
- @hybrid_property
- def name(self):
- return self.first_name
- @name.setter
- def name(self, value):
- self.first_name = value
- class FirstNameLastName(FirstNameOnly):
- # ...
- last_name = Column(String)
- @FirstNameOnly.name.getter
- def name(self):
- return self.first_name + ' ' + self.last_name
- @name.setter
- def name(self, value):
- self.first_name, self.last_name = value.split(' ', 1)
Above, the FirstNameLastName
class refers to the hybrid fromFirstNameOnly.name
to repurpose its getter and setter for the subclass.
When overriding hybrid_property.expression()
andhybrid_property.comparator()
alone as the first reference to thesuperclass, these names conflict with the same-named accessors on the class-level QueryableAttribute
object returned at the class level. Tooverride these methods when referring directly to the parent class descriptor,add the special qualifier hybrid_property.overrides
, which will de-reference the instrumented attribute back to the hybrid object:
- class FirstNameLastName(FirstNameOnly):
- # ...
- last_name = Column(String)
- @FirstNameOnly.name.overrides.expression
- def name(cls):
- return func.concat(cls.first_name, ' ', cls.last_name)
New in version 1.2: Added hybrid_property.getter()
as well as theability to redefine accessors per-subclass.
Hybrid Value Objects
Note in our previous example, if we were to compare the word_insensitive
attribute of a SearchWord
instance to a plain Python string, the plainPython string would not be coerced to lower case - theCaseInsensitiveComparator
we built, being returned by@word_insensitive.comparator
, only applies to the SQL side.
A more comprehensive form of the custom comparator is to construct a HybridValue Object. This technique applies the target value or expression to a valueobject which is then returned by the accessor in all cases. The value objectallows control of all operations upon the value as well as how compared valuesare treated, both on the SQL expression side as well as the Python value side.Replacing the previous CaseInsensitiveComparator
class with a newCaseInsensitiveWord
class:
- class CaseInsensitiveWord(Comparator):
- "Hybrid value representing a lower case representation of a word."
- def __init__(self, word):
- if isinstance(word, basestring):
- self.word = word.lower()
- elif isinstance(word, CaseInsensitiveWord):
- self.word = word.word
- else:
- self.word = func.lower(word)
- def operate(self, op, other):
- if not isinstance(other, CaseInsensitiveWord):
- other = CaseInsensitiveWord(other)
- return op(self.word, other.word)
- def __clause_element__(self):
- return self.word
- def __str__(self):
- return self.word
- key = 'word'
- "Label to apply to Query tuple results"
Above, the CaseInsensitiveWord
object represents self.word
, which maybe a SQL function, or may be a Python native. By overriding operate()
andclause_element()
to work in terms of self.word
, all comparisonoperations will work against the “converted” form of word
, whether it beSQL side or Python side. Our SearchWord
class can now deliver theCaseInsensitiveWord
object unconditionally from a single hybrid call:
- class SearchWord(Base):
- __tablename__ = 'searchword'
- id = Column(Integer, primary_key=True)
- word = Column(String(255), nullable=False)
- @hybrid_property
- def word_insensitive(self):
- return CaseInsensitiveWord(self.word)
The word_insensitive
attribute now has case-insensitive comparison behavioruniversally, including SQL expression vs. Python expression (note the Pythonvalue is converted to lower case on the Python side here):
- >>> print Session().query(SearchWord).filter_by(word_insensitive="Trucks")
- SELECT searchword.id AS searchword_id, searchword.word AS searchword_word
- FROM searchword
- WHERE lower(searchword.word) = :lower_1
SQL expression versus SQL expression:
- >>> sw1 = aliased(SearchWord)
- >>> sw2 = aliased(SearchWord)
- >>> print Session().query(
- ... sw1.word_insensitive,
- ... sw2.word_insensitive).\
- ... filter(
- ... sw1.word_insensitive > sw2.word_insensitive
- ... )
- SELECT lower(searchword_1.word) AS lower_1,
- lower(searchword_2.word) AS lower_2
- FROM searchword AS searchword_1, searchword AS searchword_2
- WHERE lower(searchword_1.word) > lower(searchword_2.word)
Python only expression:
- >>> ws1 = SearchWord(word="SomeWord")
- >>> ws1.word_insensitive == "sOmEwOrD"
- True
- >>> ws1.word_insensitive == "XOmEwOrX"
- False
- >>> print ws1.word_insensitive
- someword
The Hybrid Value pattern is very useful for any kind of value that may havemultiple representations, such as timestamps, time deltas, units ofmeasurement, currencies and encrypted passwords.
See also
Hybrids and Value Agnostic Types- on the techspot.zzzeek.org blog
Value Agnostic Types, Part II -on the techspot.zzzeek.org blog
Building Transformers
A transformer is an object which can receive a Query
object andreturn a new one. The Query
object includes a methodwith_transformation()
that returns a new Query
transformed bythe given function.
We can combine this with the Comparator
class to produce one typeof recipe which can both set up the FROM clause of a query as well as assignfiltering criterion.
Consider a mapped class Node
, which assembles using adjacency list into ahierarchical tree pattern:
- from sqlalchemy import Column, Integer, ForeignKey
- from sqlalchemy.orm import relationship
- from sqlalchemy.ext.declarative import declarative_base
- Base = declarative_base()
- class Node(Base):
- __tablename__ = 'node'
- id = Column(Integer, primary_key=True)
- parent_id = Column(Integer, ForeignKey('node.id'))
- parent = relationship("Node", remote_side=id)
Suppose we wanted to add an accessor grandparent
. This would return theparent
of Node.parent
. When we have an instance of Node
, this issimple:
- from sqlalchemy.ext.hybrid import hybrid_property
- class Node(Base):
- # ...
- @hybrid_property
- def grandparent(self):
- return self.parent.parent
For the expression, things are not so clear. We’d need to construct aQuery
where we join()
twice along Node.parent
toget to the grandparent
. We can instead return a transforming callablethat we’ll combine with the Comparator
class to receive anyQuery
object, and return a new one that’s joined to theNode.parent
attribute and filtered based on the given criterion:
- from sqlalchemy.ext.hybrid import Comparator
- class GrandparentTransformer(Comparator):
- def operate(self, op, other):
- def transform(q):
- cls = self.__clause_element__()
- parent_alias = aliased(cls)
- return q.join(parent_alias, cls.parent).\
- filter(op(parent_alias.parent, other))
- return transform
- Base = declarative_base()
- class Node(Base):
- __tablename__ = 'node'
- id =Column(Integer, primary_key=True)
- parent_id = Column(Integer, ForeignKey('node.id'))
- parent = relationship("Node", remote_side=id)
- @hybrid_property
- def grandparent(self):
- return self.parent.parent
- @grandparent.comparator
- def grandparent(cls):
- return GrandparentTransformer(cls)
The GrandparentTransformer
overrides the core Operators.operate()
method at the base of the Comparator
hierarchy to return a query-transforming callable, which then runs the given comparison operation in aparticular context. Such as, in the example above, the operate
method iscalled, given the Operators.eq
callable as well as the right side ofthe comparison Node(id=5)
. A function transform
is then returned whichwill transform a Query
first to join to Node.parent
, then tocompare parent_alias
using Operators.eq
against the left and rightsides, passing into Query.filter
:
- >>> from sqlalchemy.orm import Session
- >>> session = Session()
- sql>>> session.query(Node).\
- ... with_transformation(Node.grandparent==Node(id=5)).\
- ... all()
SELECT node.id AS node_id, node.parent_id AS node_parent_id FROM node JOIN node AS node_1 ON node_1.id = node.parent_id WHERE :param_1 = node_1.parent_id
We can modify the pattern to be more verbose but flexible by separating the“join” step from the “filter” step. The tricky part here is ensuring thatsuccessive instances of GrandparentTransformer
use the sameAliasedClass
object against Node
. Below we use a simplememoizing approach that associates a GrandparentTransformer
with eachclass:
- class Node(Base):
- # ...
- @grandparent.comparator
- def grandparent(cls):
- # memoize a GrandparentTransformer
- # per class
- if '_gp' not in cls.__dict__:
- cls._gp = GrandparentTransformer(cls)
- return cls._gp
- class GrandparentTransformer(Comparator):
- def __init__(self, cls):
- self.parent_alias = aliased(cls)
- @property
- def join(self):
- def go(q):
- return q.join(self.parent_alias, Node.parent)
- return go
- def operate(self, op, other):
- return op(self.parent_alias.parent, other)
- sql>>> session.query(Node).\
- ... with_transformation(Node.grandparent.join).\
- ... filter(Node.grandparent==Node(id=5))
SELECT node.id AS node_id, node.parent_id AS node_parent_id FROM node JOIN node AS node_1 ON node_1.id = node.parent_id WHERE :param_1 = node_1.parent_id
The “transformer” pattern is an experimental pattern that starts to make usageof some functional programming paradigms. While it’s only recommended foradvanced and/or patient developers, there’s probably a whole lot of amazingthings it can be used for.
API Reference
- class
sqlalchemy.ext.hybrid.
hybridmethod
(_func, expr=None) - Bases:
sqlalchemy.orm.base.InspectionAttrInfo
A decorator which allows definition of a Python object method with bothinstance-level and class-level behavior.
init
(func, expr=None)- Create a new
hybrid_method
.
Usage is typically via decorator:
- from sqlalchemy.ext.hybrid import hybrid_method
- class SomeClass(object):
- @hybrid_method
- def value(self, x, y):
- return self._value + x + y
- @value.expression
- def value(self, x, y):
- return func.some_function(self._value, x, y)
- class
sqlalchemy.ext.hybrid.
hybridproperty
(_fget, fset=None, fdel=None, expr=None, custom_comparator=None, update_expr=None) - Bases:
sqlalchemy.orm.base.InspectionAttrInfo
A decorator which allows definition of a Python descriptor with bothinstance-level and class-level behavior.
init
(fget, fset=None, fdel=None, expr=None, custom_comparator=None, update_expr=None)- Create a new
hybrid_property
.
Usage is typically via decorator:
- from sqlalchemy.ext.hybrid import hybrid_property
- class SomeClass(object):
- @hybrid_property
- def value(self):
- return self._value
- @value.setter
- def value(self, value):
- self._value = value
comparator
(comparator)- Provide a modifying decorator that defines a customcomparator producing method.
The return value of the decorated method should be an instance ofComparator
.
Note
The hybrid_property.comparator()
decoratorreplaces the use of the hybrid_property.expression()
decorator. They cannot be used together.
When a hybrid is invoked at the class level, theComparator
object given here is wrapped inside of aspecialized QueryableAttribute
, which is the same kind ofobject used by the ORM to represent other mapped attributes. Thereason for this is so that other class-level attributes such asdocstrings and a reference to the hybrid itself may be maintainedwithin the structure that’s returned, without any modifications to theoriginal comparator object passed in.
Note
when referring to a hybrid property from an owning class (e.g.SomeClass.some_hybrid
), an instance ofQueryableAttribute
is returned, representing theexpression or comparator object as this hybrid object. However,that object itself has accessors called expression
andcomparator
; so when attempting to override these decorators on asubclass, it may be necessary to qualify it using thehybrid_property.overrides
modifier first. See thatmodifier for details.
deleter
(fdel)Provide a modifying decorator that defines a deletion method.
- Provide a modifying decorator that defines a SQL-expressionproducing method.
When a hybrid is invoked at the class level, the SQL expression givenhere is wrapped inside of a specialized QueryableAttribute
,which is the same kind of object used by the ORM to represent othermapped attributes. The reason for this is so that other class-levelattributes such as docstrings and a reference to the hybrid itself maybe maintained within the structure that’s returned, without anymodifications to the original SQL expression passed in.
Note
when referring to a hybrid property from an owning class (e.g.SomeClass.some_hybrid
), an instance ofQueryableAttribute
is returned, representing theexpression or comparator object as well as this hybrid object.However, that object itself has accessors called expression
andcomparator
; so when attempting to override these decorators on asubclass, it may be necessary to qualify it using thehybrid_property.overrides
modifier first. See thatmodifier for details.
See also
Defining Expression Behavior Distinct from Attribute Behavior
New in version 1.2.
The hybrid_property.overrides
accessor just returnsthis hybrid object, which when called at the class level froma parent class, will de-reference the “instrumented attribute”normally returned at this level, and allow modifying decoratorslike hybrid_property.expression()
andhybrid_property.comparator()
to be used without conflicting with the same-named attributesnormally present on the QueryableAttribute
:
- class SuperClass(object):
- # ...
- @hybrid_property
- def foobar(self):
- return self._foobar
- class SubClass(SuperClass):
- # ...
- @SuperClass.foobar.overrides.expression
- def foobar(cls):
- return func.subfoobar(self._foobar)
New in version 1.2.
See also
Reusing Hybrid Properties across Subclasses
setter
(fset)Provide a modifying decorator that defines a setter method.
- Provide a modifying decorator that defines an UPDATE tupleproducing method.
The method accepts a single value, which is the value to berendered into the SET clause of an UPDATE statement. The methodshould then process this value into individual column expressionsthat fit into the ultimate SET clause, and return them as asequence of 2-tuples. Each tuplecontains a column expression as the key and a value to be rendered.
E.g.:
- class Person(Base):
- # ...
- first_name = Column(String)
- last_name = Column(String)
- @hybrid_property
- def fullname(self):
- return first_name + " " + last_name
- @fullname.update_expression
- def fullname(cls, value):
- fname, lname = value.split(" ", 1)
- return [
- (cls.first_name, fname),
- (cls.last_name, lname)
- ]
New in version 1.2.
- class
sqlalchemy.ext.hybrid.
Comparator
(expression) - Bases:
sqlalchemy.orm.interfaces.PropComparator
A helper class that allows easy construction of customPropComparator
classes for usage with hybrids.
sqlalchemy.ext.hybrid.
HYBRIDMETHOD
= symbol('HYBRIDMETHOD')- Symbol indicating an
InspectionAttr
that’sof typehybrid_method
.
Is assigned to the InspectionAttr.extension_type
attribute.
See also
Mapper.all_orm_attributes
sqlalchemy.ext.hybrid.
HYBRIDPROPERTY
= symbol('HYBRIDPROPERTY')- Symbol indicating an
InspectionAttr
that’s - of type
hybrid_method
.
- Symbol indicating an
Is assigned to the InspectionAttr.extension_type
attribute.
See also
Mapper.all_orm_attributes