You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django模型数据树形视图异常:仅显示父节点子节点空白

问题分析

你的代码存在两个核心问题导致子节点无法显示:

  1. 视图层字典键赋值错误:循环中始终用固定字符串'cat'作为group的键,每次循环都会覆盖之前的数据,最终group里仅保留最后一个分类的模板数据。
  2. 模板层取值错误:模板中group.cat是取键为'cat'的值,而非当前循环的分类变量cat对应的数据。
修复步骤

1. 修正views.py代码

将group的键改为当前循环的分类值,同时可优化查询减少数据库访问次数:

方案一:用itertools.groupby优化查询(仅1次数据库请求)

from itertools import groupby

def opnoteAnnotatorHome(request):
    # 一次性获取所需字段并按分类排序
    templates = operationTemplates.objects.order_by('templateCategory').values(
        'templateCategory', 'templateName'
    )
    # 按分类分组
    group = {}
    for cat, items in groupby(templates, key=lambda x: x['templateCategory']):
        group[cat] = list(items)
    
    # 直接从group中获取分类列表
    categoryList = group.keys()
    
    context = {
        'categoryList': categoryList,
        'group': group
    }
    return render(request, 'opnoteAnnotatorHome.html', context)

方案二:修正原循环逻辑(保留原查询方式)

def opnoteAnnotatorHome(request):
    group = {}
    categoryList = operationTemplates.objects.order_by().values_list('templateCategory', flat=True).distinct()
    for cat in categoryList:
        # 用当前分类值作为字典键,而非固定字符串'cat'
        group[cat] = operationTemplates.objects.filter(templateCategory=cat).values()

    context = {
        'categoryList': categoryList,
        'group': group
    }
    return render(request, 'opnoteAnnotatorHome.html', context)

2. 修正模板代码

通过group[cat]获取当前分类对应的模板列表,同时调整HTML结构保证层级合理性:

<td colspan="2">
{% for cat in categoryList %} 
  <ul class="parent_node">   
      <li>
          <span class="caret">{{ cat }}</span>
          <ul class="nested_child">
              {% for x in group[cat] %}
                <li>{{ x.templateName }}</li>
              {% endfor %}
          </ul>
      </li>
  </ul>
{% endfor %}
</td>

注意:将id="parent_node"改为class="parent_node",避免循环生成重复ID违反HTML规范。

额外优化建议
  • 给operationTemplates模型的templateCategory字段添加索引,提升查询效率:
templateCategory = models.CharField(max_length=255, blank=True, null=True, db_index=True)

内容的提问来源于stack exchange,提问作者KevsAI

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 06:03:19