Coder Perfect

Using sqlalchemy, you may filter several columns.


What is the best way to merge two columns and apply a filter? I want to search both the “firstname” and “lastname” columns at the same time, for example. If you only want to search one column, here’s how I’ve been doing it:

query = meta.Session.query(User).filter(

Asked by teggy

Solution #1

It can be done in a variety of ways:

Using the filter() method (and operator)

query = meta.Session.query(User).filter(,

Using the filter by() method (and operator)

query = meta.Session.query(User).filter_by(,

Chaining filter() or filter_by() (and operator)

query = meta.Session.query(User).\

Using the functions or_(), and_(), and not_() ()

from sqlalchemy import and_, or_, not_

query = meta.Session.query(User).filter(

Answered by Vlad Bezden

Solution #2

Filter can be called numerous times:

query = meta.Session.query(User).filter( \

Answered by David Johnstone

Solution #3

The or_ function in SQLAlchemy can be used to search over many columns (the underscore is required to distinguish it from Python’s own or).

Here’s an example:

from sqlalchemy import or_
query = meta.Session.query(User).filter(or_(,

Answered by gclj5

Solution #4

A piece of code that can be used on several columns. This can also be used if the application needs to integrate search functionality on a conditional basis.

search_key = "abc"
search_args = [col.ilike('%%%s%%' % search_key) for col in ['col1', 'col2', 'col3']]
query = Query(table).filter(or_(*search_args))

Note: the %% are important to skip % formatting the query.

Answered by Azharullah Shariff

Post is based on