1.準備視圖函數search()html
2.修改base.html 中搜索輸入框所在的sql
<form action="{{ url_for('search') }}" method="get">app
<input name="q" type="text" placeholder="請輸入關鍵字">函數
<div style="padding: 0 500px 50px 450px;" > <form action="{{ url_for('search') }}" method="get" class="bs-example bs-example-form" role="form"> <div class="col-lg-6"> <div class="input-group"> <input name="q" type="text" class="form-control" placeholder="請輸入關鍵字"> <span class="input-group-btn"> <button class="btn btn-default" type="submit"> 搜索 </button> </span> </div><!-- /input-group --> </div><!-- /.col-lg-6 --> </form> </div>
3.完成視圖函數search()url
@app.route('/search') def search(): qu=request.args.get('q') ques=Question.query.filter(Question.title.contains(qu)).order_by('-creat_time') return render_template('shouye.html',question=ques)
4.組合條件查詢
from sqlalchemy import or_, and_spa
@app.route('/search/') def search(): qu = request.args.get('q') ques = Question.query.filter( or_( Question.title.contains(qu), Question.detail.constraints(qu) ) ).order_by('creat_time') return render_template('shouye.html', question=ques)
運行結果爲:code