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 相关文章推荐
合并百度影音的离线数据( with python 2.3)
Aug 04 Python
python 基本数据类型占用内存空间大小的实例
Jun 12 Python
tensorflow: variable的值与variable.read_value()的值区别详解
Jul 30 Python
浅谈python之新式类
Aug 12 Python
Windows 64位下python3安装nltk模块
Sep 19 Python
Python3编码问题 Unicode utf-8 bytes互转方法
Oct 26 Python
把pandas转换int型为str型的方法
Jan 29 Python
使用django和vue进行数据交互的方法步骤
Nov 11 Python
pytorch实现用CNN和LSTM对文本进行分类方式
Jan 08 Python
python使用nibabel和sitk读取保存nii.gz文件实例
Jul 01 Python
如何利用Python写个坦克大战
Nov 18 Python
Python实现粒子群算法的示例
Feb 14 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
IIS6的PHP最佳配置方法
2007/03/19 PHP
PHP 快速排序算法详解
2014/11/10 PHP
PHP学习笔记(二):变量详解
2015/04/17 PHP
php获取远程图片并下载保存到本地的方法分析
2016/10/08 PHP
让ie6也支持websocket采用flash封装实现
2013/02/18 Javascript
js中方法重载如何实现?以及函数的参数问题
2013/08/01 Javascript
jQuery圆形统计图开发实例
2015/01/04 Javascript
JavaScript的Polymer框架中dom-repeat与VM的相关操作
2015/07/29 Javascript
浅谈JavaScript 的执行顺序
2015/08/07 Javascript
JS 日期与时间戮相互转化的简单实例
2016/06/22 Javascript
浅谈jquery页面初始化的4种方式
2016/11/27 Javascript
JavaScript中各数制转换全面总结
2017/08/21 Javascript
详解ES6之async+await 同步/异步方案
2017/09/19 Javascript
微信小程序实现YDUI的ScrollNav组件
2018/02/02 Javascript
详解vue 路由跳转四种方式 (带参数)
2019/04/28 Javascript
js实现窗口全屏示例详解
2019/09/17 Javascript
vue实现扫码功能
2020/01/17 Javascript
[40:06]DOTA2亚洲邀请赛 4.3 突围赛 Liquid vs VGJ.T 第一场
2018/04/04 DOTA
Python数据结构与算法之图的最短路径(Dijkstra算法)完整实例
2017/12/12 Python
python的dataframe和matrix的互换方法
2018/04/11 Python
python多行字符串拼接使用小括号的方法
2020/03/19 Python
kali中python版本的切换方法
2019/07/11 Python
Python统计分析模块statistics用法示例
2019/09/06 Python
使用 django orm 写 exists 条件过滤实例
2020/05/20 Python
基于Python的图像阈值化分割(迭代法)
2020/11/20 Python
CSS实现圆形放大镜狙击镜效果 只有圆圈里的放大
2012/12/10 HTML / CSS
实例讲解使用CSS实现多边框和透明边框的方法
2015/09/08 HTML / CSS
Html5 页面适配iPhoneX(就是那么简单)
2019/09/05 HTML / CSS
canvas生成带二维码海报的踩坑记录
2019/09/11 HTML / CSS
马来西亚网上购物平台:ezbuy
2018/02/13 全球购物
德国童装购物网站:NICKI´S.com
2018/04/20 全球购物
Juicy Couture Beauty官方网站:香水和化妆品
2019/03/12 全球购物
学校介绍信范文
2014/01/14 职场文书
测试工程师程序员求职信范文
2014/02/20 职场文书
教师个人考察材料
2014/12/16 职场文书
保送生自荐信
2015/03/06 职场文书