AZhao
AZhao

Reputation: 14435

Like Operator in SQLAlchemy default to wildcard

Is there a way to use the .like sqlalchemy function to return everything?

I've tried something like

session.query(Foo).filter(Foo.Bar.like('%'))

but this is returning only values that have a value in column Bar of Foo. I want to write a function that has a default keyword argument value of '%' or a wildcard so that it can be used to filter data as needed.

I have looked at the docs without success :(http://docs.sqlalchemy.org/en/rel_0_9/core/sqlelement.html#sqlalchemy.sql.operators.ColumnOperators.match

Upvotes: 5

Views: 6130

Answers (1)

Yaroslav Admin
Yaroslav Admin

Reputation: 14535

You don't need to apply filter at all if you want to return all data. Use if statement to apply filter conditionally:

def my_func(pattern=None):
    query = session.query(Foo)

    if pattern is not None:
        query = query.filter(Foo.Bar.like(pattern))

    return query

Upvotes: 7

Related Questions