我正在尝试实施“高级搜索”,但为了这个问题,我会更简单一点。
到目前为止的工作原理:
@app.route('/advanced_search', methods=['GET', 'POST'])
def advanced_search():
form = AdvancedProductSearch() # this is a SelectMultipleField
countries = ['Canada', 'France', 'Mexico', 'Nigeria']
form.categories.choices = [(c,c) for c in countries]
if form.validate_on_submit():
countrydata = form.countries.data
res = models.Product.query.filter(models.Product.country.in_(countrydata)).all()
# Now I have my search results, what do I do with them?
return render_template('advanced_search.html', title='Advanced Search', form=form)
我的计划是必须有另一种观点:advanced_search_results
,应该用于渲染结果,但我不知道它应该如何运作。
@app.route('/advanced_search_results', methods=['GET', 'POST'])
def advanced_search_results(query):
#what to do?
return render_template('advanced_search_results.html', title='Search Results')
我可以想到两种方法:
1)以某种方式将res中的所有数据行传递到advanced_search_results()
视图,但我不知道如何做到这一点。
2)使用重定向将所需的搜索查询传递给advanced_search_results()
并在那里进行数据库搜索。我也不确定该怎么做。
答案 0 :(得分:0)
只需返回必要的视图:
res = models.Product.query.filter(models.Product.country.in_(countrydata)).all()
# Now I have my search results, let's send them back
return render_template('advanced_search_results.html', title='Results',
results=res)
然后,在您的视图中,您可以像对任何其他模型列表一样循环结果:
{% for result in results %}
{{ result.name }}<br>
{{ result.country }}<br>
<hr noshade>
{% endfor %}
或者,如果您想将其托管在其他网址上,只需将action
页面上的表单的advanced-search
更改为指向advanced-search-results
:
<form action="/advanced_search_results" method="post">
{# etc ... #}
</form>
然后您可以验证搜索并显示结果或重定向用户并显示错误消息:
@app.route('/advanced_search_results', methods=['POST'])
def advanced_search_results():
form = AdvancedProductSearch()
countries = ['Canada', 'France', 'Mexico', 'Nigeria']
form.categories.choices = [(c,c) for c in countries]
if not form.validate_on_submit():
flash("There were errors with your submission")
return redirect(url_for('advanced_search'))
countrydata = form.countries.data
res = models.Product.query.filter(models.Product.country.in_(countrydata)).all()
return render_template('advanced_search_results.html',
title='Search Results',
results=res)
这使您的advanced_search
方法更简单:
@app.route('/advanced_search', methods=['GET'])
def advanced_search():
form = AdvancedProductSearch() # this is a SelectMultipleField
countries = ['Canada', 'France', 'Mexico', 'Nigeria']
form.categories.choices = [(c,c) for c in countries]
return render_template('advanced_search.html', title='Advanced Search', form=form)