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

 更新时间:2018年01月23日 10:05:34   作者:W-D  
本篇文章主要介绍了Django实现组合搜索的方法示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

一、实现方法

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附上简图:

四、其他变化

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

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基础编程小实例之计算圆的面积

    Python是最常用的编程语言,这种语言就是一种可以快速开发应用的解释型语言,有些用户不知道该怎么在Python编程里计算圆的面积,现在就给大家具体解释一下,下面这篇文章主要给大家介绍了关于python基础编程小实例之计算圆的面积的相关资料,需要的朋友可以参考下
    2023-03-03
  • Python GUI 图形用户界面

    Python GUI 图形用户界面

    这篇文章主要介绍了Python GUI 图形用户界面,图形用户界面是指采用图形方式显示的计算机操作用户界面,详细介绍需要的小伙伴可以参考一下下面文章详情
    2022-07-07
  • Python获取时间戳的几种方法详细示例

    Python获取时间戳的几种方法详细示例

    这篇文章主要给大家介绍了关于Python获取时间戳的几种方法,时间戳通常是一个字符序列,唯一地标识某一刻的时间,文中通过代码示例介绍的非常详细,需要的朋友可以参考下
    2023-10-10
  • 使用Python找出水仙花数的方法介绍

    使用Python找出水仙花数的方法介绍

    水仙花数也被称为超完全数字不变数、自恋数、自幂数、阿姆斯壮数或阿姆斯特朗数,水仙花数是指一个3位数,本文就给大家简单聊聊如何使用Python找出水仙花数,感兴趣的同学可以参考阅读
    2023-07-07
  • Numpy中stack(),hstack(),vstack()函数用法介绍及实例

    Numpy中stack(),hstack(),vstack()函数用法介绍及实例

    这篇文章主要介绍了Numpy中stack(),hstack(),vstack()函数用法介绍及实例,具有一定借鉴价值,需要的朋友可以参考下
    2018-01-01
  • Python中字典的缓存池

    Python中字典的缓存池

    这篇文章主要介绍了Python中字典的缓存池,字典的缓存池采用数组实现的,并且容量也是80个,下文详细介绍需要的小伙伴可以参考一下
    2022-05-05
  • 提升Python代码质量巧妙整理包引入顺序

    提升Python代码质量巧妙整理包引入顺序

    在Python编程中,优化导入包的顺序可以提高代码的可读性、可维护性和性能,一个良好的导入顺序不仅使代码更易于理解,还可以帮助减少潜在的循环依赖和提高导入速度,本文将介绍如何快速、有效地优化Python导入包的顺序,并提供丰富的示例代码以帮助更好地理解
    2024-01-01
  • 探索Python fcntl模块文件锁和文件控制的强大工具使用实例

    探索Python fcntl模块文件锁和文件控制的强大工具使用实例

    这篇文章主要介绍了Python fcntl模块文件锁和文件控制的强大工具使用实例探索,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2024-01-01
  • Python Pipeline处理数据工作原理探究

    Python Pipeline处理数据工作原理探究

    如果你是一个Python开发者,你可能听过"pipeline"这个术语,但 pipeline 到底是什么,它又有什么用呢?在这篇文章中,我们将探讨 Python 中的 pipeline 概念,它们是如何工作的,以及它们如何帮助你编写更清晰、更高效的代码
    2024-01-01
  • 详解python中 os._exit() 和 sys.exit(), exit(0)和exit(1) 的用法和区别

    详解python中 os._exit() 和 sys.exit(), exit(0)和exit(1) 的用法和区别

    这篇文章主要介绍了详解python中 os._exit() 和 sys.exit(), exit(0)和exit(1) 的用法和区别的相关资料,需要的朋友可以参考下
    2017-06-06

最新评论