1. 程式人生 > >實現搜索功能(2017.12.19)

實現搜索功能(2017.12.19)

imp order end port ret 17.1 .cn base nta

2 修改base.html 中搜索輸入框所在的

<form action="{{ url_for(‘search‘) }}" method="get">

<input name="q" type="text" placeholder="請輸入關鍵字">

 <form action="{{ url_for(‘search‘)}}" method="get" class="navbar-form navbar-left" role="search">
                <div class="form-group">
                    <input type="
text" id="q" name="q" autocomplete="off" placeholder="搜索" class="search-input" data-mounted="1">

1 準備視圖函數search()

3 完成視圖函數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(-creat_time)
    return render_template(shouye.html,questions=ques)


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

from sqlalchemy import or_, and_

示例:

Lobby.query.filter(

or_(

and_(

Lobby.id == Team.lobby_id,

LobbyPlayer.team_id == Team.id,

LobbyPlayer.player_id == player.steamid

),

and_(

Lobby.id == spectator_table.c.lobby_id,

spectator_table.c.player_id == player.steamid

)

)

)

結果如下:

技術分享圖片

技術分享圖片

實現搜索功能(2017.12.19)