网络编程
位置:首页>> 网络编程>> Python编程>> django列表筛选功能的实现代码

django列表筛选功能的实现代码

作者:sinat_14977477  发布时间:2021-06-23 08:48:57 

标签:django,列表,筛选

views,中设置请求的类型


class LawDetailView(View):
def get(self, request, law_id):
 type = request.GET.get('type', '')
 law = Law.objects.get(id=law_id)

return render(request, 'zcfg-detail.html', {
  'law': law,
  'type': type,
 })

templates,中设置:


<div class="col-lg-12" style="margin-bottom: 20px;">
   <a class="{% if type == '' %}btn btn-danger{% else %}btn btn-default{% endif %}" href="?type=" rel="external nofollow" role="button">全部</a>
   <a class="{% if type == 'fl' %}btn btn-danger{% else %}btn btn-default{% endif %}" href="?type=fl" rel="external nofollow" role="button">法律</a>
   <a class="{% if type == 'xzfg' %}btn btn-danger{% else %}btn btn-default{% endif %}" href="?type=xzfg" rel="external nofollow" role="button">行政法规</a>
   <a class="{% if type == 'bmgz' %}btn btn-danger{% else %}btn btn-default{% endif %}" href="?type=bmgz" rel="external nofollow" role="button">部门规章</a>
   <a class="{% if type == 'dfgz' %}btn btn-danger{% else %}btn btn-default{% endif %}" href="?type=dfgz" rel="external nofollow" role="button">地方规章</a>
</div>

补充知识:django 一种动态查询的便捷实现过程

问题引出

你可能遇到这种情况,在前端页面上有查询功能,要查询的输入选择有A,B,C等,可以通过任意一个查询,或者任意组合进行查询。

在后端,你可以使用request.GET['A']获取传入的数值。

我们需要判断哪个有输入,再在数据库中进行查询,这样比较麻烦。

解决方案

动态实现查询过程


kwargs = {}
if A is not None:
kwargs['name__startWith'] = A
if B is not None:
kwargs['address__contains'] = B
if C is not None:
kwargs['mobile__endWith'] = C
...
...
personList = Person.objects.filter(**kwargs)
...

注:

A B C 等,为前端传输过来的数据

name address mobile 等,需为你要查询的表的属性字段

startWith contains endWith 等,为你要筛选的规则

Person 为model 表名

来源:https://blog.csdn.net/sinat_14977477/article/details/81436015

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com