Phil
Phil

Reputation: 14651

SQLAlchemy querying function

I've got a function, which takes a single argument, runs a query and in the end returns some values after certain calculations.

My query is something similar to this:

def my_function(passed_argument):
    query = Session.query(t).filter(t.column_c == passed_argument).all()
    # ... do some work with query
    return some_value

What I would like to achieve however is to: Pass the function a list (instead of a single argument) which contains multiple values and for t.column_c to match any of those.

Ex. Select * from t where column_c = my_list[0] or column_c = my_list[1] or column_c = my_list[2] .. and so on.

What's the way to do this?

Thank you.

Upvotes: 0

Views: 177

Answers (2)

coproc
coproc

Reputation: 6247

You could put that filtering into the query using the SQL keyword IN:

SELECT col1 FROM table WHERE col1 IN (2,3,5,7)
SELECT col2 FROM table WHERE col2 IN ('text1','text2')

Upvotes: 1

Wolph
Wolph

Reputation: 80031

I would recommend something like this:

def my_function(*passed_arguments):
    query = Session.query(t).filter(t.column_c.in_(passed_arguments)).all()
    # ... do some work with query
    return some_value

You can call the method like this:

my_function(123, 456, 789)

Upvotes: 2

Related Questions