1.准备视图函数search()
1 # 模糊查找 2 @app.route('/search', methods=['GET', 'POST']) 3 def search(): 4 qu = request.args.get('q') 5 query = Book.query.filter( 6 or_( 7 Book.title.contains(qu), 8 Book.content.contains(qu), 9 ) 10 ).order_by('-createdate').all() 11 classfly = Classification.query.all() 12 context = { 13 'books': query, 14 'classfly':classfly 15 } 16 return render_template('home.html', **context)
2.修改base.html 中搜索输入框所在的
<form action="{{ url_for('search') }}" method="get">
<input name="q" type="text" placeholder="请输入关键字">
1 <form method="get" action="{{ url_for('search') }}"> 2 <div class="layui-row"> 3 <div class="layui-col-md3" style="padding-left: 10px;"> 4 <input type="text" name="q" required lay-verify="required" 5 placeholder="请输入搜索内容" 6 autocomplete="off" class="layui-input"> 7 </div> 8 <div class="layui-col-md3" style="padding-left: 10px;"> 9 <button type="submit" class="layui-btn layui-btn-primary">搜索</button> 10 </div> 11 </div> 12 </form>
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) - 组合条件查询
from sqlalchemy import or_, and_
https://stackoverflow.com/questions/13370993/sqlalchemy-query-and-or-issue
1 query = Book.query.filter( 2 or_( 3 Book.title.contains(qu), 4 Book.content.contains(qu), 5 ) 6 ).order_by('-createdate').all()
搜索python:
搜索Python结果: