實現搜索功能


  1. 準備視圖函數search()
  2. 修改base.html 中搜索輸入框所在的
    1. <form action="{{ url_for('search') }}" method="get">
    2.    <input name="q" type="text" placeholder="請輸入關鍵字">

  3. 完成視圖函數search()
    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)

  4. 組合條件查詢
    from sqlalchemy import or_, and_

 

示例:html

Lobby.query.filter(sql

    or_(app

        and_(ide

            Lobby.id == Team.lobby_id,函數

            LobbyPlayer.team_id == Team.id,url

            LobbyPlayer.player_id == player.steamidspa

        ),code

      and_(orm

            Lobby.id == spectator_table.c.lobby_id,htm

            spectator_table.c.player_id == player.steamid

        )

    )

)

https://stackoverflow.com/questions/13370993/sqlalchemy-query-and-or-issue

py:
from sqlalchemy import or_,and_
@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('-creat_time')
    return render_template('index.html',questions=ques)

daohang.html:

 <form action="{{ url_for('search') }}" method="get"  class="navbar-form navbar-left">
        <input name="q" type="text" class="form-control" placeholder="請輸入關鍵字">
        <button type="submit" class="btn btn-default"><span class="glyphicon glyphicon-search" aria-hidden="true"></span>查找</button>
    </form>

相關文章
相關標籤/搜索