django组合搜索实现过程详解(附代码)


Posted in Python onAugust 06, 2019

一.简介

  • # 组合搜索
  • # 技术方向:自动化,测试,运维,前端
  • # 分类:Python Linux JavaScript OpenStack Node.js GO
  • # 级别:初级 中级 高级 骨灰级

有4张表:

Direction(技术方向标),Classification(技术分类表),Level(难度级别表),Video(视频表)

它们的关系是:

Direction与Classification多对多关系

Video与Classification,Level是一对多关系

最终要实现的结果如下图:

django组合搜索实现过程详解(附代码)

二.models代码

class Direction(models.Model):
  """
  技术方向:自动化,测试,运维,前端
  """
  name = models.CharField(verbose_name='名称', max_length=32)
  classification = models.ManyToManyField('Classification')

  class Meta:
    # 重命名表名,不要自动添加的app名
    db_table = 'Direction'
    verbose_name_plural = '方向(视频方向)'
  def __str__(self):
    return self.name
class Classification(models.Model):
  """
  分类:Python Linux JavaScript OpenStack Node.js GO
  """
  name = models.CharField(verbose_name='名称', max_length=32)
  class Meta:
    db_table = 'Classification'
    verbose_name_plural = '分类(视频分类)'

  def __str__(self):
    return self.name
class Level(models.Model):
  title = models.CharField(max_length=32)

  class Meta:
    db_table = 'Level'
    verbose_name_plural = '难度级别'

  def __str__(self):
    return self.title
class Video(models.Model):
  status_choice = (
    (1, '下线'),
    (2, '上线'),
  )
  status = models.IntegerField(verbose_name='状态', choices=status_choice, default=1)
  level = models.ForeignKey(Level)
  classification = models.ForeignKey('Classification', null=True, blank=True)
  weight = models.IntegerField(verbose_name='权重(按从大到小排列)', default=0)
  title = models.CharField(verbose_name='标题', max_length=32)
  summary = models.CharField(verbose_name='简介', max_length=32)
  # img = models.ImageField(verbose_name='图片', upload_to='./static/images/Video/')
  img = models.CharField(verbose_name='图片', max_length=32)
  href = models.CharField(verbose_name='视频地址', max_length=256)
  create_date = models.DateTimeField(auto_now_add=True)
  class Meta:
    db_table = 'Video'
    verbose_name_plural = '视频'
  def __str__(self):
    return self.title

三.url路由代码

urlpatterns=[
  url(r'^admin',admin.site.urls),
  #利用的是有名分组的方法,分别获取不同的id
  url(r'^video-(?P<direction_id>(\d+))-(?P<classification_id>(\d+))-(?P<level_id>(\d+)).html$', views.video,
    name='video')
]

四.视图代码

def video(request,*args,**kwargs):
  condition = {}
  for k, v in kwargs.items():
    temp = int(v)
    kwargs[k] = temp
  print(kwargs) # (?P<direction_id>(\d+))-(?P<classification_id>(\d+))-(?P<level_id>(\d+))
  # 构造查询字典
  direction_id = kwargs.get('direction_id')
  classification_id = kwargs.get('classification_id')
  level_id = kwargs.get('level_id')
  # 获取所有的技术方向
  direction_list = models.Direction.objects.all()
  # 当没有选择技术方向时,就获取所有分类
  if direction_id == 0:
    class_list = models.Classification.objects.all()
    # 当没有选择分类时,不做什么
    if classification_id == 0:
      pass
    else:
      # 否则就将分类id放入字典
      condition['classification_id'] = classification_id
  else:
    # 当选择了技术方向id时,查询出该技术方向下的所有分类
    direction_obj = models.Direction.objects.filter(id=direction_id).first()
    class_list = direction_obj.classification.all()
    # 只获取该方向下的分类id
    vlist = direction_obj.classification.all().values_list('id')
    # 下面的代码为了生成condition是传入的一对多查询id,如:{'classification_id__in': (1, 2, 3), 'level_id': 1}
    if not vlist:
      classification_id_list = []
    else:
      # 将vlist转换成列表
      classification_id_list = list(zip(*vlist))[0]
    if classification_id == 0:
      condition['classification_id__in'] = classification_id_list
    else:
      if classification_id in classification_id_list:
        condition['classification_id'] = classification_id
      else:
        #指定技术方向:[1,2,3]  分类:5
        kwargs['classification_id'] = 0
        condition['classification_id__in'] = classification_id_list

  if level_id == 0:
    pass
  else:
    condition['level_id'] = level_id
  level_list = models.Level.objects.all()
  video_list = models.Video.objects.filter(**condition)
  # 技术方向的queryset对象列表
  print(direction_list)
  # 分类的queryset对象列表
  print(class_list)
  # 等级的queryset对象列表
  print(level_list)
  # video的queryset对象列表
  print(video_list)
  # 技术方向的id,分类的id,等级的id组成的字典
  print(kwargs)
  return render(
    request,
    'video.html',
    {
      'direction_list':direction_list,
      'class_list':class_list,
      'level_list':level_list,
      'video_list':video_list,
      'kwargs':kwargs,
    }
  )

五.模板代码

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
    .condition a {
      display: inline-block;
      padding: 5px 8px;
      border: 1px solid #dddddd;
    }
    .condition a.active {
      background-color: coral;
      color: white;
    }
  </style>
</head>
<body>
<div class="condition">
  <h1>筛选</h1>
  <div>
    {% if kwargs.direction_id == 0 %}
      {#反向解析#}
      <a href="{% url " rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" video" direction_id=0 classification_id=kwargs.classification_id level_id=kwargs.level_id %}"
        class="active">全部</a>
    {% else %}
      <a href="{% url " rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" video" direction_id=0 classification_id=kwargs.classification_id level_id=kwargs.level_id %}">全部</a>
    {% endif %}
    {% for item in direction_list %}
      {% if item.id == kwargs.direction_id %}
        <a href="{% url " rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" video" direction_id=item.id classification_id=kwargs.classification_id level_id=kwargs.level_id %}"
          class="active">{{ item.name }}</a>
      {% else %}
        <a href="{% url " rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" video" direction_id=item.id classification_id=kwargs.classification_id level_id=kwargs.level_id %}">{{ item.name }}</a>
      {% endif %}
    {% endfor %}
  </div>
  <div>
    {% if kwargs.classification_id == 0 %}
      <a href="/video-{{ kwargs.direction_id }}-0-{{ kwargs.level_id }}.html" rel="external nofollow" rel="external nofollow" class="active">全部</a>
    {% else %}
      <a href="/video-{{ kwargs.direction_id }}-0-{{ kwargs.level_id }}.html" rel="external nofollow" rel="external nofollow" >全部</a>
    {% endif %}
    {% for item in class_list %}
      {% if item.id == kwargs.classification_id %}
        <a href="/video-{{ kwargs.direction_id }}-{{ item.id }}-{{ kwargs.level_id }}.html" rel="external nofollow" rel="external nofollow" 
          class="active">{{ item.name }}</a>
      {% else %}
        <a href="/video-{{ kwargs.direction_id }}-{{ item.id }}-{{ kwargs.level_id }}.html" rel="external nofollow" rel="external nofollow" >{{ item.name }}</a>
      {% endif %}
    {% endfor %}
  </div>
  <div>
    {% if kwargs.level_id == 0 %}
      <a href="/video-{{ kwargs.direction_id }}-{{ kwargs.classification_id }}-0.html" rel="external nofollow" rel="external nofollow" class="active">全部</a>
    {% else %}
      <a href="/video-{{ kwargs.direction_id }}-{{ kwargs.classification_id }}-0.html" rel="external nofollow" rel="external nofollow" >全部</a>
    {% endif %}
    {% for item in level_list %}
      {% if item.id == kwargs.level_id %}
        <a href="/video-{{ kwargs.direction_id }}-{{ kwargs.classification_id }}-{{ item.id }}.html" rel="external nofollow" rel="external nofollow" 
          class="active">{{ item.title }}</a>
      {% else %}
        <a href="/video-{{ kwargs.direction_id }}-{{ kwargs.classification_id }}-{{ item.id }}.html" rel="external nofollow" rel="external nofollow" >{{ item.title }}</a>
      {% endif %}
    {% endfor %}
  </div>
</div>
<div>
  <h1>结果</h1>
  {% for row in video_list %}
    <div>{{ row.title }}</div>
  {% endfor %}
</div>
</body>
</html>

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

Python 相关文章推荐
Python深入学习之特殊方法与多范式
Aug 31 Python
Python写的Tkinter程序屏幕居中方法
Mar 10 Python
python判断windows系统是32位还是64位的方法
May 11 Python
Python验证文件是否可读写代码分享
Dec 11 Python
详解Python字典小结
Oct 20 Python
django中使用POST方法获取POST数据
Aug 20 Python
Python实现微信机器人的方法
Sep 06 Python
PyTorch预训练的实现
Sep 18 Python
Python sys模块常用方法解析
Feb 20 Python
python 安装库几种方法之cmd,anaconda,pycharm详解
Apr 08 Python
浅析python 定时拆分备份 nginx 日志的方法
Apr 27 Python
Python如何使用神经网络进行简单文本分类
Feb 25 Python
使用Python自动生成HTML的方法示例
Aug 06 #Python
Django RBAC权限管理设计过程详解
Aug 06 #Python
python虚拟环境完美部署教程
Aug 06 #Python
python批量图片处理简单示例
Aug 06 #Python
Python实用库 PrettyTable 学习笔记
Aug 06 #Python
浅谈django2.0 ForeignKey参数的变化
Aug 06 #Python
Python中调用其他程序的方式详解
Aug 06 #Python
You might like
使用PHP获取网络文件的实现代码
2010/01/01 PHP
php 模拟 asp.net webFrom 按钮提交事件的思路及代码
2013/12/02 PHP
THINKPHP支持YAML配置文件的设置方法
2015/03/17 PHP
js中几种去掉字串左右空格的方法
2006/12/25 Javascript
js 加载时自动调整图片大小
2008/05/28 Javascript
js,jQuery 排序的实现代码,网页标签排序的实现,标签排序
2011/04/27 Javascript
JavaScript高级程序设计 阅读笔记(十七) js事件
2012/08/14 Javascript
利用Jquery实现可多选的下拉框
2014/02/21 Javascript
JavaScript通过正则表达式实现表单验证电话号码
2014/03/07 Javascript
两种方法基于jQuery实现IE浏览器兼容placeholder效果
2014/10/14 Javascript
JS中setTimeout的巧妙用法前端函数节流
2016/03/24 Javascript
js/jquery控制页面动态加载数据 滑动滚动条自动加载事件的方法
2017/02/08 Javascript
浅谈angularjs中响应回车事件
2017/04/24 Javascript
layui中layer前端组件实现图片显示功能的方法分析
2017/10/13 Javascript
vue中使用vue-router切换页面时滚动条自动滚动到顶部的方法
2017/11/28 Javascript
基于 flexible 的 Vue 组件:Toast -- 显示框效果
2017/12/26 Javascript
CSS3结合jQuery实现动画效果及回调函数的实例
2017/12/27 jQuery
Vue 使用中的小技巧
2018/04/26 Javascript
vue系列之requireJs中引入vue-router的方法
2018/07/18 Javascript
详解jQuery获取特殊属性的值以及设置内容
2018/11/14 jQuery
使用JQuery自动完成插件Auto Complete详解
2019/06/18 jQuery
github配置使用指南
2014/11/18 Python
python数据结构之图的实现方法
2015/07/08 Python
Python二叉树的定义及常用遍历算法分析
2017/11/24 Python
Pipenv一键搭建python虚拟环境的方法
2018/05/22 Python
浅谈Pandas:Series和DataFrame间的算术元素
2018/12/22 Python
python绘制多个子图的实例
2019/07/07 Python
python3.6 tkinter实现屏保小程序
2019/07/30 Python
html5 viewport使用方法示例详解
2013/12/02 HTML / CSS
浅谈HTML5新增和废弃的标签
2019/04/28 HTML / CSS
德国在线订购鲜花:Fleurop
2018/08/25 全球购物
社区居务公开实施方案
2014/03/27 职场文书
政法干警核心价值观心得体会
2014/09/11 职场文书
2016年学校爱国卫生月活动总结
2016/04/06 职场文书
React + Threejs + Swiper 实现全景图效果的完整代码
2021/06/28 Javascript
Redis中有序集合的内部实现方式的详细介绍
2022/03/16 Redis