Pyramid+SQLAlchemy: create filter with multiple OR conditions

…my first step with Python…

When you add filter with multiple criterion conditions joined by AND, you simply put all conditions one after one separated by comma:

query = DBSession.query(SomeTable).filter(
                SomeTable.name.contains(search_str),
                SomeTable.description.contains(search_str),
                SomeTable.another_field.contains(search_str)
        )

But in case you need to join filter conditions with OR, the way is more tricky… I found this approach working for me:

Add import:

from sqlalchemy import or_

And then, your filter should look like this:

query = DBSession.query(SomeTable).filter(
            or_(
                SomeTable.name.contains(search_str),
                SomeTable.name.contains(search_string2),
                SomeTable.description.contains(search_str),
                SomeTable.another_field.contains(search_str)
            )
        )

Enjoy!

This entry was posted on Monday, July 9th, 2012 at 09:17 and is filed under Python. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.





Leave a Reply


required


required (will not be published)