django模型查詢數(shù)據(jù)每一行增加一個屬性值方法
方法一: 通過for循環(huán)為每一行信息增加一個值 如下:
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文件中執(zhí)行PY文件中的函數(shù))
1、在應(yīng)用目錄下創(chuàng)建 templatetags 目錄(目錄名只能是 templatetags)。
2, 在 templatetags 目錄下創(chuàng)建任意 py 文件,如:zhuangzi_tags.py。
3, 創(chuàng)建內(nèi)容如下:
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 的最上方中導(dǎo)入該 py 文件。
{% load static %} {% load zhuangzi_tags %}
在 HTML 中使用自定義過濾器。
{{ row.sort.sortpath | getParentsName }}