django模型查询数据每一行增加一个属性值方法
方法一: 通过for循环为每一行信息增加一个值 如下:
result = News.objects.all() total = result.count() for index, row in enumerate(result) : setattr(result[index],"parSorts",SortAll.getParentName(row.sort.sortpath)) return render(request,'zz/news/list1.html',locals())
模板访问:
{{ row.sort.parSorts }}
方法二: 自定义过滤器(可以在HTML文件中执行PY文件中的函数)
1、在应用目录下创建 templatetags 目录(目录名只能是 templatetags)。
2, 在 templatetags 目录下创建任意 py 文件,如:zhuangzi_tags.py。
3, 创建内容如下:
from django import template from zz.dbs import Sorts register = template.Library()#register的名字是固定的,不可改变 @register.filter def getParentsName(sortpath): str = "" if sortpath: sortpath = sortpath[2:len(sortpath) - 1] list = sortpath.split(",") for index in range(len(list)): row = Sorts.objects.get(id=list[index]) if index == 0: str += row.name else: str += "->" + row.name return str
修改 settings.py 文件的 TEMPLATES 选项配置,添加 libraries 配置:
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], "libraries": { # 添加这边三行配置 'zhuangzi_tags': 'templatetags.zhuangzi_tags' # 添加这边三行配置 }# 添加这边三行配置 }, }, ]
在使用自定义过滤器前,要在 html 文件 body 的最上方中导入该 py 文件。
{% load static %} {% load zhuangzi_tags %}
在 HTML 中使用自定义过滤器。
{{ row.sort.sortpath | getParentsName }}