I want to get the value of a parameter in a sqlalchemy query object dynamically:
q = session.query(Model).filter(Model.foo = 6)
I now want to be able to retrieve the value 6 from q
assert(q.magic == 6)
Attempts:
print(q._criterion) # -> models.foo = :foo_1
But where is the value of foo_1?
SQLAlchemy generates a tree structure from your filter predicates, appending each leaf on as appropriate and putting the result in
Query._criterion. You can explore this with theget_children()method of variousClauseElementandColumnElementclasses.For
Model.foo == 6you’ll end up with something like this:If you were to & together two predicates, like
(Model.foo == 6) & (Model.name == 'a name')or by chainingfiltercalls, you’d get aBooleanClauseListwith two_BinaryExpressionchildren. This means you can’t hard code a simple expression to reliably return the values you want but instead have to traverse the predicate tree.The
traversefunction fromsqlalchemy.sql.visitorsdoes just that, relying on a dictionary of special names that relate each Element’s__visit_name__attribute to a processing function. This is a breadth-first traversal, which as you can see is appropriate for the example below; there’s also a depth-first version available.The following function shows how to generate a list of column-parameter pairs from a given query. I adapted it from the Beaker caching example: