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

在Django中如何按日期对表单记录进行分组展示

解决方案

方法1:使用Django模板自带regroup标签(无需修改视图代码,最简单)

无需改动现有views.py逻辑,直接修改模板即可,regroup标签可直接对已排序的查询集按指定字段完成分组:

{% regroup lists by date as date_groups %}
{% for group in date_groups %}
<div class="req-list">
<h6>{{ group.grouper }}</h6>
   <table class="table table-striped">
     <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">食物类型</th>
      <th scope="col">卡路里</th>
      <th scope="col">蛋白质</th>
      <th scope="col">碳水化合物</th>
      <th scope="col">饮品</th>
      <th scope="col">水果</th>
      <th scope="col">备注</th>
    </tr>
  </thead>
  <tbody>
    {% for item in group.list %}
    <tr>
      <th scope="row">{{ item.id }}</th>
      <td>{{ item.food_type }}</td>
      <td>{{ item.calorie }}</td>
      <td>@{{ item.protein }}</td>
        <td>@{{ item.carbohydrate }}</td>
        <td>@{{ item.drinks }}</td>
        <td>@{{ item.fruits }}</td>
        <td>@{{ item.note }}</td>
    </tr>
    {% endfor %}
  </tbody>
</table>
    </div>
{% endfor %}

如果需要保留原波斯语表头,直接替换<th>标签内的中文即可。


方法2:视图层预处理分组数据

如果需要在后端提前处理分组逻辑,可使用itertools.groupby对已按日期排序的查询集做分组:

  1. 修改后的views.py代码:
import itertools
import datetime
from django.shortcuts import render
from .models import Form

def requests(request):
    lists = Form.objects.all().order_by('-date')
    # 按日期分组
    date_groups = []
    for date, items in itertools.groupby(lists, key=lambda x: x.date):
        date_groups.append({
            'date': date,
            'items': list(items)
        })
    context = {
        'date_groups': date_groups
    }
    return render(request, 'form/requests_list.html', context)
  1. 对应模板代码:
{% for group in date_groups %}
<div class="req-list">
<h6>{{ group.date }}</h6>
   <table class="table table-striped">
     <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">食物类型</th>
      <th scope="col">卡路里</th>
      <th scope="col">蛋白质</th>
      <th scope="col">碳水化合物</th>
      <th scope="col">饮品</th>
      <th scope="col">水果</th>
      <th scope="col">备注</th>
    </tr>
  </thead>
  <tbody>
    {% for item in group.items %}
    <tr>
      <th scope="row">{{ item.id }}</th>
      <td>{{ item.food_type }}</td>
      <td>{{ item.calorie }}</td>
      <td>@{{ item.protein }}</td>
        <td>@{{ item.carbohydrate }}</td>
        <td>@{{ item.drinks }}</td>
        <td>@{{ item.fruits }}</td>
        <td>@{{ item.note }}</td>
    </tr>
    {% endfor %}
  </tbody>
</table>
    </div>
{% endfor %}

两种方案都支持新增记录自动归入对应日期分组,无需额外修改逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 06:36:00