组合搜索

1:n的情况

1. 模型:视频、分类、级别

2. 关系:视频(n):分类(1)、视频(n):级别(1)

3. 新建一个项目 mysite

4. 新建一个应用 app01

5. 在mysite项目下新建一个文件夹 static

6. 在mysite项目下新建一个文件夹 templates (备注:如果使用IDE创建项目,则该文件夹会自动生成)

7. 在app01应用下新建一个文件夹 templatetags

8. 在models.py中新增模型类

from django.db import models


class Level(models.Model):
    """级别表"""
    name = models.CharField(max_length=32)

    def __str__(self):
        return self.name


class Category(models.Model):
    """分类表"""
    name = models.CharField(max_length=32)
    def __str__(self):
        return self.name

class Video(models.Model):
    """视频表"""
    lv = models.ForeignKey(Level)
    cg = models.ForeignKey(Category)

    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/')
    href = models.CharField(verbose_name='视频地址', max_length=256)

    create_date = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

9. 在admin.py中注册模型类

from django.contrib import admin
from app01 import models

admin.site.register(models.Level)
admin.site.register(models.Category)
admin.site.register(models.Video)

10. 修改mysite应用下的settings.py文件

""" 第1步 添加应用"""
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app01',
]

""" 第2步 配置静态文件路径"""
STATIC_URL = '/static/'
STATICFILES_DIRS=(
    os.path.join(BASE_DIR,'static'),
)

11. 在mysite项目下的urls.py文件中新增路由

from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^video1-(?P<cg_id>\d+)-(?P<lv_id>\d+).html', views.video1,name='vvv'),
]

12. 在templates文件夹下新建一个video.html文件

{% load xx %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .filter a{
            display: inline-block;
            margin: 5px;
            padding: 3px 5px;
        }
        .filter a.active{
            background-color: brown;
            color: white;
        }
    </style>
</head>
<body>
    <h1>筛选条件</h1>
    <div class="filter">
        <div>
            {% total_tag arg_dict "cg_id" %}
            {% for item in category_list %}
                {% category_tag item arg_dict %}
            {% endfor %}
        </div>
        <div>
            {% total_tag arg_dict "lv_id" %}
            {% for item in level_list %}
                {% level_tag item arg_dict %}
            {% endfor %}
        </div>
    </div>

    <h1>查询结果</h1>
    <div class="content">
        {% for row in result %}
            <div style="width: 100px;height: 260px;float: left;">
                <img style="width: 100px;height: 150px;" src="{{ row.img }}">
                <p>{{ row.title }}</p>
                <p>{{ row.summary }}</p>
            </div>
        {% endfor %}
    </div>

</body>
</html>

13. 在app01应用下的views.py文件中新增视图函数video1

from django.shortcuts import render, HttpResponse
from app01 import models


def video1(request, *args, **kwargs):
    """ 通过别名vvv反向生成url
        from django.urls import reverse
        url = reverse('vvv', kwargs={'cg_id': 1, 'lv_id': 2})
        print(url)
    """
    condition = {}
    for k, v in kwargs.items():
        if v == '0':
            pass
        else:
            condition[k] = v
    category_list = models.Category.objects.all()   # 获取所有分类
    level_list = models.Level.objects.all()    # 获取所有级别

    result = models.Video.objects.filter(**condition)
    return render(request,
                  'video1.html', {
                      'category_list': category_list,
                      'level_list': level_list,
                      'result': result,
                      'arg_dict': kwargs
                  })

14. 在templatetags文件夹下新建xx.py

from django import template
from django.utils.safestring import mark_safe

register = template.Library()


@register.simple_tag
def category_tag(obj,arg_dict):
    """ 生成分类的a标签 """
    # 通过别名vvv反向生成url
    from django.urls import reverse
    url = reverse('vvv', kwargs={'cg_id': obj.id, 'lv_id': arg_dict.get('lv_id')})

    if str(obj.id) == arg_dict.get('cg_id'):
        # 获取当前URL
        tag = "<a class='active' href='%s'>%s</a>" %(url,obj.name)
        return mark_safe(tag)
    else:
        tag = "<a href='%s'>%s</a>" % (url, obj.name)
        return mark_safe(tag)

@register.simple_tag
def level_tag(obj,arg_dict):
   """ 生成级别的a标签 """

    from django.urls import reverse
    url = reverse('vvv', kwargs={'cg_id': arg_dict.get('cg_id'), 'lv_id': obj.id})

    if str(obj.id) == arg_dict.get('lv_id'):
        tag = "<a class='active' href='%s'>%s</a>" %(url,obj.name)
        return mark_safe(tag)
    else:
        tag = "<a href='%s'>%s</a>" % (url, obj.name)
        return mark_safe(tag)

@register.simple_tag
def total_tag(arg_dict,key):
   """ 生成全部的a标签 """

    from django.urls import reverse
    if key == 'cg_id':
        url = reverse('vvv', kwargs={'cg_id': 0, 'lv_id': arg_dict.get('lv_id')})
    elif key == 'lv_id':
        url = reverse('vvv', kwargs={'cg_id': arg_dict.get('cg_id'), 'lv_id': 0})
    else:
        url = ""

    tag = "<a href='%s'>全部</a>" % (url,)
    return mark_safe(tag)

备注:自定义tagde使用

 


 

n:n的情况

1. 模型:视频、分类、级别、方向

2. 关系:方向(n):分类(n)

3. 新建一个项目 mysite

4. 新建一个应用 app01

5. 在mysite项目下新建一个文件夹 static

6. 在mysite项目下新建一个文件夹 templates (备注:如果使用IDE创建项目,则该文件夹会自动生成)

7. 在app01应用下新建一个文件夹 templatetags

8. 在models.py中新增模型类

from django.db import models


class Level(models.Model):
    """ 级别表 """
    name = models.CharField(max_length=32)

    def __str__(self):
        return self.name

class Direction(models.Model):
    """ 反向表表 """
    name = models.CharField(max_length=32)
    d_2_c = models.ManyToManyField('Category')

class Category(models.Model):
    """ 分类表 """
    name = models.CharField(max_length=32)
    def __str__(self):
        return self.name

class Video(models.Model):
    """ 视频表 """
    lv = models.ForeignKey(Level)
    cg = models.ForeignKey(Category)

    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/')
    href = models.CharField(verbose_name='视频地址', max_length=256)

    create_date = models.DateTimeField(auto_now_add=True)
    def __str__(self):
        return self.title 

9. 在admin.py中注册模型类

from django.contrib import admin
from app01 import models

admin.site.register(models.Level)
admin.site.register(models.Category)
admin.site.register(models.Video)
admin.site.register(models.Direction)

10. 修改mysite应用下的settings.py文件

"""第1步 添加应用"""
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app01',
]

"""第2步 添加静态文件路径"""
STATIC_URL = '/static/'
STATICFILES_DIRS=(
    os.path.join(BASE_DIR,'static'),
)

11. 在mysite项目下的urls.py文件中新增路由

from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^video2-(?P<dr_id>\d+)-(?P<cg_id>\d+)-(?P<lv_id>\d+).html', views.video2,name='vvv2'),
]

12. 在templates文件夹下新建一个video2.html文件

{% load xx %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .filter a{
            display: inline-block;
            margin: 5px;
            padding: 3px 5px;
        }
        .filter a.active{
            background-color: brown;
            color: white;
        }
    </style>
</head>
<body>
    <h1>筛选条件</h1>
    <div class="filter">
        <div>
            {% total_tag_2 arg_dict 'dr_id' %}
            {% for item in drection_list %}
                <!-- if判断,如果kwargs.dr_id = item.id
                    - 加入样式
                else:
                    - 无样式
                   -->
                {% dr_tag item arg_dict %}
            {% endfor %}

        </div>
        <div>
            {% total_tag_2 arg_dict 'cg_id' %}
            {% for item in category_list %}
                {% cg_tag item arg_dict %}
            {% endfor %}
        </div>
        <div>
            {% total_tag_2 arg_dict 'lv_id' %}
            {% for item in level_list %}
                {% lv_tag item arg_dict %}
            {% endfor %}
        </div>
    </div>

    <h1>查询结果</h1>
    <div class="content">
        {% for row in result %}
            <div style="width: 100px;height: 260px;float: left;">
                <img style="width: 100px;height: 150px;" src="{{ row.img }}">
                <p>{{ row.title }}</p>
                <p>{{ row.summary }}</p>
            </div>
        {% endfor %}
    </div>

</body>
</html>

13. 在app01应用下的views.py文件中新增视图函数video2

from django.shortcuts import render, HttpResponse
from app01 import models


def video2(request, *args, **kwargs):
    # 0-0-0.html
    # 0-1-0.html
    # 1-0-0.html
    # 1-1-0.html [1,2,3,4]
    # 2-1-0.html [2,3,4]
dr_id = kwargs.get('dr_id') cg_id = kwargs.get('cg_id') lv_id = kwargs.get('lv_id') condition = {} drection_list = models.Direction.objects.all() level_list = models.Level.objects.all() if dr_id == "0": # 未选择方向 category_list = models.Category.objects.all() if cg_id == '0': # 未选择分类 pass else: # 选择分类 # models.Video.objects.filter(cg_id=cg_id) condition['cg_id'] = cg_id else: # 选择了方向 category_list = models.Category.objects.filter(direction=dr_id) temp = category_list.values_list('id') cg_id_list = list(zip(*temp))[0] if cg_id == '0': # 未选择分类 condition['cg_id__in'] = cg_id_list else: # 选择了分类 if int(cg_id) in cg_id_list: condition['cg_id'] = cg_id else: condition['cg_id__in'] = cg_id_list kwargs['cg_id'] = '0' if lv_id == '0': pass else: condition['lv_id'] = lv_id result = models.Video.objects.filter(**condition) print(result) return render(request, 'video2.html', { 'drection_list': drection_list, 'level_list': level_list, 'category_list': category_list, 'arg_dict':kwargs })

14. 在templatetags文件夹下新建xx.py

from django import template
from django.utils.safestring import mark_safe

register = template.Library()

@register.simple_tag
def dr_tag(obj,arg_dict):
    """ 生成方向的a标签 """

    from django.urls import reverse
    url = reverse('vvv2', kwargs={'dr_id': obj.id, 'cg_id': arg_dict.get('cg_id'), 'lv_id': arg_dict.get('lv_id')})

    if str(obj.id) == arg_dict.get('dr_id'):
        # 获取当前URL
        tag = "<a class='active' href='%s'>%s</a>" %(url,obj.name)
        return mark_safe(tag)
    else:
        tag = "<a href='%s'>%s</a>" % (url, obj.name)
        return mark_safe(tag)


@register.simple_tag
def cg_tag(obj,arg_dict):
    """ 生成分类的a标签 """

    from django.urls import reverse
    url = reverse('vvv2', kwargs={'dr_id': arg_dict.get('dr_id'), 'cg_id': obj.id, 'lv_id': arg_dict.get('lv_id')})

    if str(obj.id) == arg_dict.get('cg_id'):
        # 获取当前URL
        tag = "<a class='active' href='%s'>%s</a>" %(url,obj.name)
        return mark_safe(tag)
    else:
        tag = "<a href='%s'>%s</a>" % (url, obj.name)
        return mark_safe(tag)



@register.simple_tag
def lv_tag(obj,arg_dict):
    """ 生成级别的a标签 """

    from django.urls import reverse
    url = reverse('vvv2', kwargs={'dr_id': arg_dict.get('dr_id'), 'cg_id': arg_dict.get('cg_id'), 'lv_id': obj.id})

    if str(obj.id) == arg_dict.get('lv_id'):
        # 获取当前URL
        tag = "<a class='active' href='%s'>%s</a>" %(url,obj.name)
        return mark_safe(tag)
    else:
        tag = "<a href='%s'>%s</a>" % (url, obj.name)
        return mark_safe(tag)


@register.simple_tag
def total_tag_2(arg_dict,key):
    """ 生成全部的a标签 """
    from django.urls import reverse
    if key == 'dr_id':
        url = reverse('vvv2', kwargs={'dr_id': 0, 'cg_id': arg_dict.get('cg_id'), 'lv_id': arg_dict.get('lv_id')})
    elif key == 'cg_id':
        url = reverse('vvv2', kwargs={'dr_id': arg_dict.get('dr_id'), 'cg_id': 0, 'lv_id': arg_dict.get('lv_id')})

    elif key == 'lv_id':
        url = reverse('vvv2', kwargs={'dr_id': arg_dict.get('dr_id'), 'cg_id': arg_dict.get('cg_id'), 'lv_id': 0})
    else:
        url = ''
    if arg_dict.get(key) == '0':
        tag = "<a class='active' href='%s'>全部</a>" % (url,)
    else:
        tag = "<a href='%s'>全部</a>" % (url,)
    return mark_safe(tag)

 

posted @ 2018-08-13 09:33  _E.t  阅读(336)  评论(0编辑  收藏  举报