实现对上图机构类别地区筛选,并且完成根据机构学习人数和课程数进行排序。
一 views.py逻辑
在views.py中,已完成的及机构定义为
all_orgs = CourseOrg.objects.all()
在其后添加过滤,代码如下:
#取出筛选城市
city_id = request.GET.get('city', "")
if city_id:
all_orgs = all_orgs.filter(city_id=int(city_id))
#取出筛选机构类别
category = request.GET.get('ct', "")
if category:
all_orgs = all_orgs.filter(category=category)
二、html中的修改
html代码如下:
<div class="cont">
<a href="?city={{ city_id }}"><span class="{% ifequal category '' %}active2{% endifequal %}">全部</span></a>
<a href="?ct=pxjg&city={{ city_id }}"><span class="{% ifequal category 'pxjg' %}active2{% endifequal %}">培训机构</span></a>
<a href="?ct=gx&city={{ city_id }}"><span class="{% ifequal category 'gx' %}active2{% endifequal %}">高校</span></a>
<a href="?ct=gr&city={{ city_id }}"><span class="{% ifequal category 'gr' %}active2{% endifequal %}">个人</span></a>
</div>
</li>
<li>
<h2>所在地区</h2>
<div class="more">更多</div>
<div class="cont">
<a href="?ct={{ category }}"><span class="{% ifequal city_id '' %}active2{% endifequal %}">全部</span></a>
{% for city in all_citys %}
<a href="?city={{ city.id }}&ct={{ category }}"><span class="{% ifequal city_id city.id|stringformat:"i" %}active2{% endifequal %}">{{ city.name }}</span></a>
{% endfor %}
</div>
首先html中需先定city.id 和ct,在href中分别加入a href=”?city={{ city.id }} a href=”?ct=pxjg等。即可实现筛选功能。
为了使点击的类别可标绿,以培训机构为例,加入以下标签
span class="{% ifequal category 'pxjg' %}active2{% endifequal %}
同时,需在“全部”这一内容下加入:
<span class="{% ifequal category '' %}active2{% endifequal %}">
此时,发现了一个问题。比如点击高校后再点击北京。机构类别并没有仍然显示高校,而是跳到了全部。故需要在html的href标签内进一步完善。
<a href="?ct=pxjg&city={{ city_id }}">
排序功能:
sort = request.GET.get('sort', "")
if sort:
if sort == "students":
all_orgs =all_orgs.order_by("-students")
elif sort == "courses":
all_orgs = all_orgs.order_by("-courses_nums")
<li class="{% if sort == 'studens' %}active{% endif %}"><a href="?sort=students&ct={{ category }}&city={{ city_id }}">学习人数 ↓</a></li>
<li class="{% if sort == 'courses '%}active{% endif %}"><a href="?sort=courses&ct={{ category }}&city={{ city_id }}">课程数 ↓</a></li>