Building an or_ filter in loop

370 views
Skip to first unread message

Bryan

unread,
May 8, 2009, 3:52:09 PM5/8/09
to sqlalchemy
I can't figure out a clean way of adding a bunch of filter terms to a
query in a loop joined by an OR clause. Successive calls to filter
join the expressions by AND. I would like to do something like the
following, but have the expressions joined by OR

terms = ['apple', 'orange', 'peach']
q = Session.query(Fruit)
for term in terms:
q = q.filter(Fruit.name.like('%' + term + '%')


Desired pseudo-sql:
SELECT * FROM fruit WHERE name like '%apple%' OR name like '%orange%'
OR name like '%peach%'

Kyle Schaffrick

unread,
May 8, 2009, 3:59:52 PM5/8/09
to sqlal...@googlegroups.com

I think this might do what you want:

cond = or_(*[ Fruit.name.like('%' + term + '%') for term in terms ])
q = Session.query(Fruit).filter(cond)

-Kyle

Bryan

unread,
May 8, 2009, 4:18:25 PM5/8/09
to sqlalchemy
That worked, thanks

polaar

unread,
May 11, 2009, 12:01:06 PM5/11/09
to sqlalchemy
this would even be easier (and correcter if the terms contain "%")
written as:

cond = or_(*[Fruit.name.contains(term) for term in terms])

Kyle Schaffrick

unread,
May 11, 2009, 2:24:19 PM5/11/09
to sqlal...@googlegroups.com
On Mon, 11 May 2009 09:01:06 -0700 (PDT)
polaar <steven.v...@gmail.com> wrote:

>
> this would even be easier (and correcter if the terms contain "%")
> written as:
>
> cond = or_(*[Fruit.name.contains(term) for term in terms])
>

Indeed, good catch. I was so interested in the "apply or_" logic that I
missed the escaping bug :)

-Kyle

Reply all
Reply to author
Forward
0 new messages