Django实现组合搜索的方法示例


Posted in Python onJanuary 23, 2018

一、实现方法

1.纯模板语言实现

2.自定义simpletag实现(本质是简化了纯模板语言的判断)

二、基本原理

原理都是通过django路由系统,匹配url筛选条件,将筛选条件作为数据库查询结果,返回给前端。

例如:路由系统中的url格式是这样:

url(r'^article-(?P<article_type_id>\d+)-(?P<category_id>\d+).html',views.filter)

其中article_type_id和category_id和数据库中字段是相对应的,此时当一个url为article-1-2.html时候,后台处理函数的参数将是一个字典{'article_type_id': 1, 'category_id': 1},然后将该条件作为数据库查询条件,最后得出结果返回给前端

三、代码样例

方法1:纯模板语言实现

urls.py

#!/usr/bin/env python3
#_*_ coding:utf-8 _*_
#Author:wd
from django.conf.urls import url

from . import views
urlpatterns = [
  url(r'^$',views.index),
  url(r'^article-(?P<article_type_id>\d+)-(?P<category_id>\d+).html',views.filter),
]

models.py

from django.db import models

class Category(models.Model):
  caption=models.CharField(max_length=64)

class Article_type(models.Model):
  caption=models.CharField(max_length=64)

class Article(models.Model):
  title=models.CharField(max_length=64)
  content=models.CharField(max_length=256)
  category=models.ForeignKey(to='Category')
  article_type=models.ForeignKey(to='Article_type'

views.py

def filter(request,*args,**kwargs):
  if request.method=="GET":
    condition={}
    for k,v in kwargs.items():
          kwargs[k]=int(v) #模板if判断row.id是数字,所以这里需要转换
          if v=="0":#当条件为0代表所选的是全部,那么就不必要加入到过滤条件中
            pass
          else:
            condition[k]=int(v)
    aritcle=models.Article.objects.filter(**condition)
    aritcle_type=models.Article_type.objects.all()
    aritcle_category=models.Category.objects.all()
    return render(request,'search.html',{
      'aritcle':aritcle,
      'article_type':aritcle_type,
      'article_category':aritcle_category,
      'article_arg':kwargs,#将当前的筛选条件传递给html
    })

html模板

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
    .container a{
      display: inline-block;
      padding: 3px 5px;
      margin: 5px;
      border: 1px solid #dddddd ;
    }
    .active{
      background-color: rebeccapurple;

    }
  </style>
</head>
<body>
<h1>搜索条件</h1>
<div class="container">
  {% if article_arg.article_type_id == 0 %}
    <a class="active" href="/cmdb/article-0-{{ article_arg.category_id }}.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >全部</a>
  {% else %}
     <a href="/cmdb/article-0-{{ article_arg.category_id }}.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >全部</a>
  {% endif %}
  {% for row in article_type %}
    {% if row.id == article_arg.article_type_id %}
      <a class="active" href="/cmdb/article-{{ row.id }}-{{ article_arg.category_id }}.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >{{ row.caption }}</a>
    {% else %}
      <a href="/cmdb/article-{{ row.id }}-{{ article_arg.category_id }}.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >{{ row.caption }}</a>
    {% endif %}
  {% endfor %}
</div>
<div class="container">
   {% if article_arg.category_id == 0 %}
    <a class="active" href="/cmdb/article-{{ article_arg.article_type_id }}-0.html" rel="external nofollow" rel="external nofollow" >全部</a>
  {% else %}
     <a href="/cmdb/article-{{ article_arg.article_type_id }}-0.html" rel="external nofollow" rel="external nofollow" >全部</a>
  {% endif %}
  {% for row in article_category %}
    {% if row.id == article_arg.category_id %}
    <a class="active" href="/cmdb/article-{{ article_arg.article_type_id }}-{{ row.id }}.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >{{ row.caption }}</a>
    {% else %}
    <a href="/cmdb/article-{{ article_arg.article_type_id }}-{{ row.id }}.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >{{ row.caption }}</a>
    {% endif %}
  {% endfor %}
</div>
<h1>查询结果</h1>
<div>
  {% for row in aritcle %}
    <div>{{ row.id }}-{{ row.title }}</div>
  {% endfor %}
</div>
</body>
</html>

方法二:使用simpletag实现

定义simpletag

myfilter.py

#!/usr/bin/env python3
#_*_ coding:utf-8 _*_
#Author:wd
from django import template
from django.utils.safestring import mark_safe

register=template.Library()
@register.simple_tag
def filter_all(article_arg,condition):
  '''
  处理条件为全部
  :param article_arg: 当前url字典:如{'article_type_id': 1, 'category_id': 1}
  :param condition: 要处理的条件,如article_type_id,用于区分当前处理选择了那个全部
  :return: 返回下面页面形式
  {% if article_arg.article_type_id == 0 %}
    <a class="active" href="/cmdb/article-0-{{ article_arg.category_id }}.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >全部</a>
  {% else %}
     <a href="/cmdb/article-0-{{ article_arg.category_id }}.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >全部</a>
  {% endif %}
  {% for row in article_type %}
    {% if row.id == article_arg.article_type_id %}
      <a class="active" href="/cmdb/article-{{ row.id }}-{{ article_arg.category_id }}.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >{{ row.caption }}</a>
    {% else %}
      <a href="/cmdb/article-{{ row.id }}-{{ article_arg.category_id }}.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >{{ row.caption }}</a>
    {% endif %}
  {% endfor %}
  '''
  if condition=='article_type_id':
    if article_arg[condition]==0:
      print(article_arg['category_id'])
      res= '<a class ="active" href="/cmdb/article-0-%s.html" rel="external nofollow" rel="external nofollow" >全部</a>' % article_arg['category_id']
    else:
      res = '<a href="/cmdb/article-0-%s.html" rel="external nofollow" rel="external nofollow" >全部</a>' % article_arg['category_id']
    return mark_safe(res)
  elif condition=='category_id':
    if article_arg['category_id']==0:
      res = '<a class ="active" href="/cmdb/article-%s-0.html" rel="external nofollow" rel="external nofollow" >全部</a>' % article_arg['article_type_id']
    else:
      res = '<a href="/cmdb/article-%s-0.html" rel="external nofollow" rel="external nofollow" >全部</a>' % article_arg['article_type_id']
    return mark_safe(res)

@register.simple_tag
def filter_type(article_type,article_arg):
  '''
  :param article_type: article_type对象
  :param article_arg: 当前url字典
  :return: 
  {% for row in article_type %}
    {% if row.id == article_arg.article_type_id %}
      <a class="active" href="/cmdb/article-{{ row.id }}-{{ article_arg.category_id }}.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >{{ row.caption }}</a>
    {% else %}
      <a href="/cmdb/article-{{ row.id }}-{{ article_arg.category_id }}.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >{{ row.caption }}</a>
    {% endif %}
  {% endfor %}
   '''
  res=[]
  for row in article_type:
    if row.id== article_arg['article_type_id']:
      temp='<a class="active" href="/cmdb/article-%s-%s.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >%s</a>' %(row.id,article_arg['category_id'],row.caption)
    else:
      temp = '<a href="/cmdb/article-%s-%s.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >%s</a>' % (row.id, article_arg['category_id'],row.caption)
    res.append(temp)
  return mark_safe("".join(res))

@register.simple_tag
def filter_category(article_category,article_arg):
  '''
  :param article_type: article_category对象
  :param article_arg: 当前url字典
  :return: 
  {% for row in article_category %}
    {% if row.id == article_arg.category_id %}
    <a class="active" href="/cmdb/article-{{ article_arg.article_type_id }}-{{ row.id }}.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >{{ row.caption }}</a>
    {% else %}
    <a href="/cmdb/article-{{ article_arg.article_type_id }}-{{ row.id }}.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >{{ row.caption }}</a>
    {% endif %}
  {% endfor %}
   '''
  res=[]
  for row in article_category:
    if row.id== article_arg['category_id']:
      temp='<a class="active" href="/cmdb/article-%s-%s.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >%s</a>' %(article_arg['article_type_id'],row.id,row.caption)
    else:
      temp = '<a href="/cmdb/article-%s-%s.html" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >%s</a>' % (article_arg['article_type_id'],row.id,row.caption)
    res.append(temp)
  return mark_safe("".join(res))

html模板

{% load myfilter %}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
    .container a{
      display: inline-block;
      padding: 3px 5px;
      margin: 5px;
      border: 1px solid #dddddd ;
    }
    .active{
      background-color: rebeccapurple;

    }
  </style>
</head>
<body>
<h1>搜索条件</h1>
<div class="container">
  {% filter_all article_arg 'article_type_id' %}
  {% filter_type article_type article_arg %}
</div>
<div class="container">
  {% filter_all article_arg 'category_id' %}
  {% filter_category article_category article_arg %}
</div>
<h1>查询结果</h1>
<div>
  {% for row in aritcle %}
    <div>{{ row.id }}-{{ row.title }}</div>
  {% endfor %}
</div>
</body>
</html>

ps附上简图:

Django实现组合搜索的方法示例

四、其他变化

在如上的示例中,我们的过滤条件是从数据库中拿到,有时候我们定义的时候使用的是静态字段,此时组合搜索会稍微修改。

1.model定义

class Article(models.Model):
  title=models.CharField(max_length=64)
  content=models.CharField(max_length=256)
  category=models.ForeignKey(to='Category')
  article_type=(  #使用静态字段放入内存
    (1,'linux'),
    (2,'python'),
    (3,'go'),
  )

2.处理函数变化

###获取####
aritcle_type=models.Article.article_type#直接获取类的静态字段

3.simpletag相应改变

###由于我们传递的元祖,所以取值使用元祖方式
article_type[0]# 筛选条件id
article_type[1]# 筛选条件名称

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python通过正则查找微博@(at)用户的方法
Mar 13 Python
Python实现登录人人网并抓取新鲜事的方法
May 11 Python
python中base64加密解密方法实例分析
May 16 Python
对pyqt5中QTabWidget的相关操作详解
Jun 21 Python
Python+pyplot绘制带文本标注的柱状图方法
Jul 08 Python
linux环境下Django的安装配置详解
Jul 22 Python
Python 画出来六维图
Jul 26 Python
Django 拆分model和view的实现方法
Aug 16 Python
python 字典访问的三种方法小结
Dec 05 Python
通过Python实现一个简单的html页面
May 16 Python
Python如何爬取qq音乐歌词到本地
Jun 01 Python
python使用正则表达式匹配txt特定字符串(有换行)
Dec 09 Python
50行Python代码实现人脸检测功能
Jan 23 #Python
Python基于OpenCV实现视频的人脸检测
Jan 23 #Python
Python求出0~100以内的所有素数
Jan 23 #Python
python之matplotlib学习绘制动态更新图实例代码
Jan 23 #Python
彻底搞懂Python字符编码
Jan 23 #Python
Python实现PS滤镜的万花筒效果示例
Jan 23 #Python
python处理csv数据动态显示曲线实例代码
Jan 23 #Python
You might like
PHP编程之设置apache虚拟目录
2016/07/08 PHP
PHP实现的日历功能示例
2018/09/01 PHP
tp5(thinkPHP5)框架连接数据库的方法示例
2018/12/24 PHP
PHP中md5()函数的用法讲解
2019/03/30 PHP
Jsonp 跨域的原理以及Jquery的解决方案
2010/05/18 Javascript
javascript AOP 实现ajax回调函数使用比较方便
2010/11/20 Javascript
使用jquery获取网页中图片高度的两种方法
2013/09/26 Javascript
JS数组去重与取重的示例代码
2014/01/24 Javascript
vue从使用到源码实现教程详解
2016/09/19 Javascript
Nodejs读取文件时相对路径的正确写法(使用fs模块)
2017/04/27 NodeJs
详解用webpack2搭建angular2的项目
2017/06/22 Javascript
实例讲解DataTables固定表格宽度(设置横向滚动条)
2017/07/11 Javascript
javaScript之split与join的区别(详解)
2017/11/08 Javascript
简单的Vue异步组件实例Demo
2017/12/27 Javascript
vue.js实现格式化时间并每秒更新显示功能示例
2018/07/07 Javascript
Jquery的Ajax技术使用方法
2019/01/21 jQuery
js核心基础之构造函数constructor用法实例分析
2019/05/11 Javascript
react native 仿微信聊天室实例代码
2019/09/17 Javascript
微信小程序实现列表滚动头部吸顶的示例代码
2020/07/12 Javascript
浅谈Series和DataFrame中的sort_index方法
2018/06/07 Python
解决python ogr shp字段写入中文乱码的问题
2018/12/31 Python
深入解析神经网络从原理到实现
2019/07/26 Python
聊聊python中的异常嵌套
2020/09/01 Python
pycharm远程连接服务器并配置python interpreter的方法
2020/12/23 Python
孕妇装中的著名品牌:Isabella Oliver(伊莎贝拉·奥利弗)
2016/10/31 全球购物
意大利在线购买隐形眼镜网站:VisionDirect.it
2019/03/18 全球购物
保险公司年会主持词
2014/03/22 职场文书
地震捐款倡议书
2014/08/29 职场文书
活动总结新闻稿
2014/08/30 职场文书
2014年宣传部工作总结
2014/11/12 职场文书
2014年底个人工作总结
2015/03/10 职场文书
和谐拯救危机观后感
2015/06/15 职场文书
中学教师读书笔记
2015/07/01 职场文书
公司庆典主持词
2015/07/04 职场文书
小学六年级毕业感言
2015/07/30 职场文书
MySQL REVOKE实现删除用户权限
2021/06/18 MySQL