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

如何在Django日程页面中显示当前及未来5天的日期?

解决方案

1. 优化视图函数

通过一次查询获取6天的所有记录并按日期分组,减少数据库请求次数,同时生成有序的日期范围:

from datetime import date, timedelta

def Schedule(request):
    today = date.today()
    # 生成当天及后续5天的日期列表(共6天)
    date_range = [today + timedelta(days=i) for i in range(6)]
    
    # 批量查询该日期范围内的所有提交记录
    end_date = today + timedelta(days=5)
    all_reports = Submissions.objects.filter(
        execution_date__range=(today, end_date)
    )
    
    # 按日期分组,构建「日期-对应记录」的字典
    reports_by_date = {}
    for target_date in date_range:
        reports_by_date[target_date] = all_reports.filter(execution_date=target_date)
    
    context = {
        'date_range': date_range,
        'reports_by_date': reports_by_date
    }
    return render(request, 'staff/work_schedule.html', context)

2. 更新模板代码

循环遍历日期范围,自动渲染每个日期的标题和对应记录,无记录时显示提示:

<div class="row no-gutters" style="width: 100%;">
    {% for current_date in date_range %}
        <div style="width: 100%;background-color: rgb(0, 0, 0);color: white;font-weight: 800;font-size: 12px;">{{ current_date }}</div>
        <table class="table table-striped table-hover">
            <tbody>
                {% for record in reports_by_date.current_date %}
                <tr style="font-size: 10px;text-align: center;">
                    <th style="width: 8%;">{{ record.client.user.get_full_name }}, tel.:{{ record.client.phone_number }}</th>
                    <th style="width: 8%;">{{ record.client.post_code }} {{ record.client.city }}, ul.{{ record.client.street }}</th>
                    <th style="width: 40%;">{{ record.contents|linebreaks|truncatewords_html:50 }}</th>
                    <th style="width: 40%;">{{ record.details_planned_service|linebreaks|truncatewords_html:50 }}</th>
                </tr>
                {% empty %}
                <tr style="font-size: 10px;text-align: center;">
                    <td colspan="4">无当日提交记录</td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    {% endfor %}
</div>

关键说明

  • 用date_range保证日期按「当天→第5天」的顺序展示,避免字典遍历的无序问题
  • 单次批量查询+分组的方式,比循环6次查询更高效
  • 新增{% empty %}标签处理空记录场景,提升页面友好性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 22:27:39