Phil
Phil

Reputation: 14671

Python definition with optional argument to query with SQLAlchemy

I have a function which receives an optional argument. I am querying a database table within this function.

What I would like is:

If the optional argument is specified, I want to add another additional .filter() to my database query.

My query line is already rather long so I don't want to do If .. else .. in which I repeat the whole query twice.

What is the way to do this?

Below is an example to my query and if my_val is specified, I need to add another filtering line.

def my_def (my_val):
    query = Session.query(Table1, Table2).\
            filter(Table1.c1.in_(some_val)).\
            filter(Table1.c2 == 113).\
            filter(Table2.c3 == val1).\
            filter(Table1.c4 == val2).\
            filter(Table2.c5 == val5).\
            all()

Upvotes: 1

Views: 2225

Answers (1)

reptilicus
reptilicus

Reputation: 10397

You can wait to call the .all() method on the query set, something like this:


def my_def (my_val=my_val):
    query = Session.query(Table1, Table2).\
            filter(Table1.c1.in_(some_val)).\
            filter(Table1.c2 == 113).\
            filter(Table2.c3 == val1).\
            filter(Table1.c4 == val2).\
            filter(Table2.c5 == val5)
    if my_val:
        query = query.filter(Table1.c6 == my_val)
    return query.all()

Upvotes: 4

Related Questions