There are several ways you can approach this way.
One way is that SQLAlchemy has a module in the Query.update () and Query.delete () methods that does this with the name sqlalchemy.orm.evaluator. It can only express a very limited set of expression operators:
>>> from sqlalchemy.orm.evaluator import EvaluatorCompiler >>> print EvaluatorCompiler().process(bool_clause)(a_foo) False >>> print EvaluatorCompiler().process(int_clause)(a_foo) 15
It does not execute more complex expressions such as in_() , however we are open to any number of reasonable operations added to this module if you want to contribute.
Now the use case that you have is usually done using hybrid properties and methods . In this case, we take advantage of Python in that when we have <anything>.someattr <some operator> <somethingelse> , we can change self and cls to <anything> . So your example:
class Foo(Base): __tablename__ = 'foo' id = Column(Integer, primary_key=True) bar = Column(Integer) @hybrid_method def bool_clause(self, other): return self.bar > other @hybrid_method def int_clause(self, other): return self.bar + other >>> a_foo = Foo(bar=5) >>> print a_foo.bool_clause(10) False >>> print a_foo.int_clause(10) 15
This actually uses the same idea as your suggestion to use lambdas, just a more expressive expression.
Both approaches can be combined. One great thing about the evaluator is that it handles joins like or_() and and_() . Without this, hybrids require you to decompose methods into instance and expression methods if you need to use something like "and" or "or".
zzzeek
source share