實現搜索功能

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

  1. 獲取搜索關鍵字
    q = request.args.get('q’)
  2. 條件查詢
    qu = Question.query.filter(Question.title.contains(q)).order_by('-creat_time’)
  3. 加載查詢結果:
    return render_template('index.html', question=qu)
@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

 

相關文章
相關標籤/搜索