python&django 实现页面中关联查询小功能(中级篇)

时间:2023-11-24 12:37:50

目的

组合搜索实现如下图功能

python&django 实现页面中关联查询小功能(中级篇)

知识点

1.使用自定义标签模板(templatetags)

实现

models.py 和 views.py和初级篇一样

重点如下:在app01目录下创建templatetags文件夹,并且创建一个.py文件,我创建了filter.py文件

 # 需要在模版中注册
from django import template
from django.utils.safestring import mark_safe
register = template.Library()
@register.simple_tag
def filter_all(arg_dict,k):
'''
{% if arg_dict.article_type_id == 0 %} {% else %}
<a href="/article-0-{{ arg_dict.category_id }}.html">全部</a>
{% endif %}
'''
ret = ""
if k == 'article_type_id':
n1 = arg_dict[k]
n2 = arg_dict['category_id']
if n1 == 0:
ret = '<a class="active" href="/article-0-%s.html">全部</a>' % n2
else:
ret = '<a href="/article-0-%s.html">全部</a>' % n2
else:
n1 = arg_dict[k]
n2 = arg_dict['article_type_id']
if n1 == 0:
ret = '<a class="active" href="/article-%s-0.html">全部</a>' % n2
else:
ret = '<a href="/article-%s-0.html">全部</a>' % n2 return mark_safe(ret) @register.simple_tag
def filter_article_type(article_type_list,arg_dict,k):
'''
{% for row in article_type_list %}
{% if row.id == arg_dict.article_type_id %}
<a class="active" href="/article-{{ row.id }}-{{ arg_dict.category_id }}.html">{{ row.caption }}</a>
{% else %}
<a href="/article-{{ row.id }}-{{ arg_dict.category_id }}.html">{{ row.caption }}</a>
{% endif %}
{% endfor %}
'''
ret = []
for row in article_type_list:
if k=='article_type_id':
if row.id == arg_dict['article_type_id']:
temp = '<a class="active" href="/article-%s-%s.html">%s</a>' % (row.id, arg_dict["category_id"], row.caption)
else:
temp = '<a href="/article-%s-%s.html">%s</a>' % (row.id, arg_dict["category_id"], row.caption)
else:
if row.id == arg_dict['category_id']:
temp = '<a class="active" href="/article-%s-%s.html">%s</a>' % ( arg_dict["article_type_id"],row.id, row.caption)
else:
temp = '<a href="/article-%s-%s.html">%s</a>' % ( arg_dict["article_type_id"],row.id, row.caption)
ret.append(temp)
return mark_safe("".join(ret))

修改html文件

article.html

 {% load filter %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.condition a{
display:inline-block;;
padding: 3px 5px;
border:1px solid #dddddd;
margin:5px 5px;
}
.condition a.active{
background-color: darkgreen;
}
</style>
</head>
<body>
<h1>过滤条件</h1>
<div class="condition">
{% filter_all arg_dict 'article_type_id' %}
{% filter_article_type category_list arg_dict 'article_type_id' %} </div>
<div class="condition">
{% filter_all arg_dict 'category_id' %}
{% filter_article_type category_list arg_dict 'category_id' %} </div>
<h1>查询结果</h1>
<ul>
{% for row in result %}
<li>{{ row.id }}-{{ row.title }}</li>
{% endfor %}
</ul>
</body>
</html>