- 准备视图函数search()
@app.route(‘/search/‘) def search(): qu = request.args.get(‘q‘) ques = Question.query.filter (or_(Question.title.contains(qu), Question.detail.contains(qu) ) ).order_by(‘-create_time‘) return render_template(‘index.html‘,question=ques)
- 修改base.html 中搜索输入框所在的
- <form action="{{ url_for(‘search‘) }}" method="get">
<input name="q" type="text" placeholder="请输入关键字">
<form class="navbar-form navbar-left" action="{{ url_for(‘search‘) }}" method="get"> <div class="form-group"> <input name="q" type="text" class="form-control" placeholder="请输入关键字"> </div> <button type="submit" class="btn btn-default" style="margin-top: 8px">搜索</button> </form>
- 完成视图函数search()
- 获取搜索关键字
q = request.args.get(‘q’) - 条件查询
qu = Question.query.filter(Question.title.contains(q)).order_by(‘-creat_time’)
- 获取搜索关键字
加载查询结果:
return render_template(‘index.html‘, question=qu)
@app.route(‘/search/‘) def search(): qu = request.args.get(‘q‘) ques = Question.query.filter (or_(Question.title.contains(qu), Question.detail.contains(qu) ) ).order_by(‘-create_time‘) return render_template(‘index.html‘,question=ques)
- 组合条件查询
from sqlalchemy import or_, and_
运行截图: