I am rather new to Flask and web development in general and am struggling to figure out how to set up arbitrary column searching.
My form:
class SearchForm(FlaskForm):
choices = [('facilityid', 'facilityid'),
('facilityname', 'facilityname'),
('networkid', 'networkid'),
('contractid', 'contractid'),
('address', 'address')]
select = SelectField('Search for something', choices=choices)
id_search = StringField('')
submit = SubmitField('Search')
My Route:
@app.route('/results')
def results(search):
search_string = search.data['id_search']
search_field = search.data['select']
# TODO: Remove redundant code
if search_string == '':
query = FGymNetworkFacilities.query.order_by(func.rand()).offset(20).limit(10).all()
table = FacilityTable(query)
table.border = True
elif search_field == 'address' and search_field != '':
query = FGymNetworkFacilities.query.filter(FGymNetworkFacilities.address.like(f'%{search_string}%')).all()
table = FacilityTable(query)
table.border = True
if not results:
flash('no results!')
return redirect('/')
return render_template('facilities.html', table=table)
This table model has around 80 columns and I'd like to not make 80 if/else
statements. I need to find a way to pass the column name to the line (in this example address
)
query = FGymNetworkFacilities.query.filter(FGymNetworkFacilities.address.like(f'%{search_string}%')).all()
But if there is a better way to do this, I'm definitely open to that. Unfortunately Elastic Search is not something I can implement given the constraints of this project and am forced to use this type of search method for now.
Thanks in advance.