[网站功能]在Flask中实现多条件分页搜索
2018-07-27 本文已影响0人
fukurao
今天我滴户外网站开发进度走到了多条件搜索活动的界面,不难但是涉及的细节很多,所以简单记录下
先上实现截图:
具体实现一步步走起~
创建Form以及Form的布局显示
这个搜索框也可以直接抛弃Form....
表单类创建了需要的field并赋值
class ActivitySearchForm(Form):
keyword = StringField('搜索关键字')
outdoor = RadioField('活动类型')
days = RadioField('出行天数')
sort = RadioField('排序方式')
submit = SubmitField('搜索活动')
def __init__(self, *args, **kwargs):
super(ActivitySearchForm, self).__init__(*args, **kwargs)
#为单选钮赋默认值
self.outdoor.choices = [(item.id, item.name) for item in OutdoorType.show_list()]
days_source = [(1, '1天'), (3, '2-3天'), (7, '4-7天'), (15, '8-15天'), (16, '16天以上')]
self.days.choices = days_source
sort_source = [(0, '最新发布'), (1, '最多访问'), (2, '价格由低到高'), (3, '价格由高到低')]
self.sort.choices = sort_source
界面选择表格布局,代码:
<form action="" method="post" class="form-horizontal" role="form">
{{ form.hidden_tag() }}
<table class="table vertical-center">
<tbody>
<tr class="active">
<td class="highlight">搜索关键字</td>
<td><div class="col-sm-6">
{{ form.keyword(class_='form-control') }}
</div>
<div class="col-sm-2">
{{ form.submit(class_='btn btn-warning') }}
</div>
</td>
</tr>
<tr class="warning">
<td class="highlight">活动类型</td>
<td>{{ form.outdoor(class_='radio-list-inline') }}</td>
</tr>
<tr class="active">
<td class="highlight">出行天数</td>
<td>{{ form.days(class_='radio-list-inline') }}</td>
</tr>
<tr class="warning">
<td class="highlight">排序类型</td>
<td>{{ form.sort(class_='radio-list-inline') }}</td>
</tr>
</tbody>
</table>
</form>
在活动类'Activity`中添加一个根据筛选项取得活动的方法
这里就是不停迭代filter_by
和order_by
这里有一点需要注意,搜索框里面的几个单选钮,如果没有选择都返回'None',是None这个字符串,而部署None类型,所以判断的时候用的都是!= 'None'
这个还值得注意的是用空白分隔的关键字做搜索的实现
最后把query构建好了,用paginate分页取回活动
@staticmethod
def get_activities_search(keyword, outdoor, days, sort, page=1):
activities = Activity.query
if outdoor != 'None': #户外类型
t = OutdoorType.query.get(int(outdoor))
activities = t.activities
if keyword:#允许多个空格分隔的搜索关键字
keywords = keyword.split()
for k in keywords:
activities = activities.filter(Activity.name.like('%'+k+'%'))
if days != 'None': #出行天数
if days == '1':
activities = activities.filter(Activity.days == 1)
elif days == '3':
activities = activities.filter(or_(Activity.days == 2, Activity.days == 3))
elif days == '7':
activities = activities.filter(and_(Activity.days > 3, Activity.days < 8))
elif days == '15':
activities = activities.filter(and_(Activity.days > 7, Activity.days < 16))
else:
activities = activities.filter(Activity.days > 15)
if sort != 'None':#排序
if sort == '1':
activities = activities.order_by(Activity.view_count.desc())
elif sort == '2':
activities = activities.order_by(Activity.price.asc())
elif sort == '3':
activities = activities.order_by(Activity.price.desc())
else:
activities = activities.order_by(Activity.timestamp.desc())
return activities.paginate(page, current_app.config['PAGECOUNT_ACTIVITY'], error_out=False)
在View里面添加处理逻辑
在分页浏览中使用session
保存搜索条件,每次POST修改搜索条件的时候,记得把page设成1
@team.route('/activites/search', methods=['GET', 'POST'])
def activities_search():
form = ActivitySearchForm()
page = request.args.get('page', 1, type=int)
if request.method == 'POST':
#每次POST,添加查询字符串,取回第一页
session['activity-keyword'] = form.keyword.data
session['activity-outdoor'] = form.outdoor.data
session['activity-days'] = form.days.data
session['activity-sort'] = form.sort.data
page = 1
pagination = Activity.get_activities_search(
session.get('activity-keyword', ""),
session.get('activity-outdoor', 'None'),
session.get('activity-days', 'None'),
session.get('activity-sort', 'None'),
page
)
activities = pagination.items
return render_template('activities_search.html',
form=form,
activities = activities,
pagination = pagination)
这里需要特别注意的是,因为使用了session
,所以在从别的页面直接跳转到搜索页时,显示的是session搜索条件下的活动,所以在跳转前要将session清空