Skip to content Skip to sidebar Skip to footer

Dynamics Or Filtering With Sqlalchemy

I have a list of of SQLAlchemy Model attributes. For example: my_list = ['firstName', 'lastName'] I also have a person SQLAlchemy Object with firstName and lastName attributes. I

Solution 1:

With SQLAlchemy this is pretty easy if you know about reduce; use getattr to get the dynamically named column from the Person class.

from functools import reduce  # python 3from operator import or_

columns = [ 'firstName', 'lastName' ]

# make a list of `Person.c.like(query+'%')`
likes = [ getattr(Person, c).like(query+'%') for c in column ]

# join them with | using reduce; does the same as likes[0]|likes[1]|....
final_filter = reduce(or_, likes)

session.filter(final_filter).all()

Though or_ also accepts any number of clauses to or together, so you can use argument unpacking too:

final_filter = or_(*likes)

Post a Comment for "Dynamics Or Filtering With Sqlalchemy"