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线程中对join方法的运用的教程
Apr 09 Python
Python中的各种装饰器详解
Apr 11 Python
Python使用pygame模块编写俄罗斯方块游戏的代码实例
Dec 08 Python
Python实现的科学计算器功能示例
Aug 04 Python
linux下python使用sendmail发送邮件
May 22 Python
tensorflow 获取变量&amp;打印权值的实例讲解
Jun 14 Python
10 行 Python 代码教你自动发送短信(不想回复工作邮件妙招)
Oct 11 Python
python如何获取当前文件夹下所有文件名详解
Jan 25 Python
Python面向对象总结及类与正则表达式详解
Apr 18 Python
python selenium 查找隐藏元素 自动播放视频功能
Jul 24 Python
谈谈Python:为什么类中的私有属性可以在外部赋值并访问
Mar 05 Python
python+selenium小米商城红米K40手机自动抢购的示例代码
Mar 24 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流量统计功能的实现代码
2012/09/29 PHP
使用 PHPMAILER 发送邮件实例应用
2012/11/07 PHP
PHP5.3的垃圾回收机制(动态存储分配方案)深入理解
2012/12/10 PHP
浅析php中常量,变量的作用域和生存周期
2013/08/10 PHP
php中的字符编码转换函数用法示例
2014/10/20 PHP
PHP语法小结之基础和变量
2015/11/22 PHP
PHP const定义常量及global定义全局常量实例解析
2020/05/28 PHP
JavaScript 异步调用框架 (Part 2 - 用例设计)
2009/08/03 Javascript
javascript写的一个链表实现代码
2009/10/25 Javascript
javascript图像处理—仿射变换深度理解
2013/01/16 Javascript
jquery 合并内容相同的单元格(示例代码)
2013/12/13 Javascript
js简单网速测试方法完整实例
2015/12/15 Javascript
在vue项目中使用md5加密的方法
2018/09/14 Javascript
jquery validate 实现动态增加/删除验证规则操作示例
2019/10/28 jQuery
JS加载解析Markdown文档过程详解
2020/05/19 Javascript
详解Python的Django框架中的通用视图
2015/05/04 Python
Python中的枚举类型示例介绍
2019/01/09 Python
python操作文件的参数整理
2019/06/11 Python
Python爬虫爬取电影票房数据及图表展示操作示例
2020/03/27 Python
Anaconda的安装及其环境变量的配置详解
2020/04/22 Python
Python使用OpenPyXL处理Excel表格
2020/07/02 Python
Python局部变量与全局变量区别原理解析
2020/07/14 Python
了解一下python内建模块collections
2020/09/07 Python
大学生旷课检讨书
2014/01/22 职场文书
趣味游戏活动方案
2014/02/07 职场文书
群众路线教育党课主持词
2014/04/01 职场文书
领导班子四风对照检查材料范文
2014/09/27 职场文书
学生抄袭作业的检讨书
2014/10/02 职场文书
财务工作失职检讨书
2014/11/21 职场文书
对外汉语教师推荐信
2015/03/27 职场文书
毕业设计工作总结
2015/08/14 职场文书
初三数学教学反思
2016/02/17 职场文书
初中政治教学反思
2016/02/23 职场文书
pyqt5蒙版遮罩mask,setmask的使用
2021/06/11 Python
Python面向对象编程之类的概念
2021/11/01 Python
Django基础CBV装饰器和中间件
2022/03/22 Python