On Fri, 8 May 2009 12:52:09 -0700 (PDT)
Bryan <[email protected]> wrote:
>
> 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%'
>
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
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"sqlalchemy" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/sqlalchemy?hl=en
-~----------~----~----~----~------~----~------~--~---