1

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()

1 Answer 1

4

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()

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.