0

I have a large sqlite table of 33k records (movies) . I want to give the user the ability to search in that table via filters . Each movie record has 10 fields : Actors, Directors, Runtime, Genre, Rating and few more . The only filters available for the user to use are people (Include Actors and Directors), Genre, Rating and Runtime .

The problem is that the user can use two filters or more, hence we don't really know which filter will be used . Filters values are passed via an HTTP req to the server which process it and create an SQL query based on filters to execute on the db .

What I can't understand is how can I create an SQL query if I don't know which filters will be used ? Because only used filters will be sent to the server .

Basically I want to find a way to create an SQL query based on sent filters by each users .

0

1 Answer 1

2

If you're given a list of filters, you can just apply Query.filter_by() or Query.filter() over and over:

filters = [
    ('rating', 3),
    ('runtime', 90),
    ('genre', 'documentary')
]

query = session.query(Movie)

for column, value in filters:
    # Make sure `column` and `value` are legal values!

    query = query.filter_by(**{column: value})

Since the query is evaluated only at the end, you're essentially doing:

query = query.filter_by(...).filter_by(...) ...

In the last line, filter_by(**{column: value}) is notation for filter_by(value_of_column_variable=value).

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.