Johnston
Johnston

Reputation: 20884

SQLAlchemy Flask, match some or all

I have a list of schools (1000's) with a name, city, and state.
There are name, city and state input fields.
I want to search for schools by name. If they leave city or state inputs empty I want to search by any city, any state. If they enter the city (leaving state blank) then search by name and city. Etc etc.

Bottom line: Search with the data that is available and everything else is "any".

Is there a quick way to do this other than writing every possible combination?

Upvotes: 0

Views: 112

Answers (1)

davidism
davidism

Reputation: 127200

I'm writing this as if you're using Flask-SQLAlchemy and WTForms.

...
schools = School.query

if form.name.data:
    schools = schools.filter(School.name == form.name.data)

if form.city.data:
    schools = schools.filter(School.city == form.city.data)

if form.state.data:
    schools = schools.filter(School.state == form.state.data)

# at this point schools is a query filtered with whatever was given
...

This is just an example, reword it, use filters besides equality, etc. I have "filter forms" like this, and would put extra methods on the form, query() and filter(query). Then they can be called like this in a view:

form = FilterForm(request.args)  # use get for filtering
schools = form.query()
if form.validate():
    schools = form.filter(schools)
return render_template('schools.html', form=form, schools=schools)

Upvotes: 3

Related Questions