Archive for the ‘Python’ Category

 

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!