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

如何在Django模板中展示包含分类/分段行的非标准表格?

如何在Django模板中展示包含分类/分段行的非标准表格?

嘿,我完全get你想实现的效果——就是把表格按name_category分成不同的区块,每个区块顶部有一个醒目的分类标题行,下面跟着对应类别的数据行对吧?其实不用额外创建中转模型哦,咱们直接在视图层对数据做分组处理,再到模板里针对性渲染就行,这样既灵活又不用维护冗余的模型数据。

我给你一步步拆解实现方法:

1. 修改视图层:按分类分组数据

首先咱们要把原查询集按name_category排序并分组,这样就能把同一分类的数据归到一起。这里用Python的itertools.groupby就很方便,记得先给查询集按分类排序(groupby要求数据是有序的):

# views.py
from itertools import groupby
from operator import itemgetter
from .models import CreateNewGPR

def your_view_name(request, pk):
    # 先过滤数据,并且按name_category排序(groupby必须依赖有序数据)
    filter_qs = CreateNewGPR.objects.filter(name_object=pk).order_by('name_category')
    
    # 按name_category分组,整理成分类+对应数据的结构
    grouped_data = []
    for category, items in groupby(filter_qs, key=itemgetter('name_category')):
        # 把每个分类下的条目转换成你需要的字段集合
        category_items = list(items.values(
            "name_working", "type_izm", "value_work", 
            "lyudi_norma", "technik_norma", "date_begin", "date_end"
        ))
        grouped_data.append({
            'category_name': category,
            'data_items': category_items
        })
    
    context = {'grouped_books': grouped_data}
    return render(request, 'your_template.html', context)

2. 调整模板:渲染分类标题+数据行

接下来在模板里,咱们循环遍历分组后的数据:先渲染跨列的分类标题行(用colspan合并所有表格列),再循环渲染该分类下的每一条数据行。还可以给分类行加样式,让它和数据行区分开:

<!-- template.html -->
<style>
  /* 给分类标题行加样式,增强区分度 */
  .category-section {
    background-color: #f5f5f5;
    font-weight: bold;
    text-align: left;
  }
  .data-row {
    border-bottom: 1px solid #eee;
  }
</style>

<div>
  <table class="pure-table">
    <thead>
      <tr>
        <th>Name Column 1</th>
        <th>Name Column 2</th>
        <th>Name Column 3</th>
        <th>Name Column 4</th>
        <th>Name Column 5</th>
        <th>Name Column 6</th>
        <th>Name Column 7</th>
      </tr>
    </thead>
    <tbody>
      {% for group in grouped_books %}
        <!-- 渲染分类标题行,合并7列 -->
        <tr class="category-section">
          <td colspan="7">{{ group.category_name }}</td>
        </tr>
        <!-- 渲染该分类下的所有数据行 -->
        {% for book in group.data_items %}
          <tr class="data-row">
            <td>{{ book.name_working }}</td>
            <td>{{ book.type_izm }}</td>
            <td>{{ book.value_work }}</td>
            <td>{{ book.lyudi_norma }}</td>
            <td>{{ book.technik_norma }}</td>
            <td>{{ book.date_begin }}</td>
            <td>{{ book.date_end }}</td>
          </tr>
        {% endfor %}
      {% endfor %}
    </tbody>
  </table>
</div>

为什么不用中转模型?

这种方式比创建中转模型更省心:

  • 不用维护额外的模型和同步数据,所有数据直接从原模型实时获取,避免数据不一致的问题
  • 分类逻辑完全在视图层处理,后续如果要调整分组规则(比如按name_working分组),只需要修改视图的分组键就行,不用动数据库结构

这样实现后,你的表格就会和你想要的效果一致——每个分类作为一个独立的区块,标题行和数据行清晰区分,总行数也会自动计算(分类数+数据行数),完全符合你的需求~

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.07 09:44:32