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

如何在Django模板中遍历某月所有日期并展示销售状态

Django整月销售日期表格实现方案

实现思路

  1. 生成目标月份的所有日期列表
  2. 从数据库查询该月份的销售记录,将日期与销售状态映射为字典(键为日期对象,值为销售状态)
  3. 模板中遍历整月日期,匹配对应销售状态,有记录则显示yes,无记录则留空

views.py 代码实现

from django.shortcuts import render
from datetime import datetime, timedelta
from .models import SaleDates

def sale_calendar(request):
    # 获取目标月份,示例为当前月份,可按需调整(比如从请求参数获取年月)
    today = datetime.today()
    target_year = today.year
    target_month = today.month

    # 计算该月第一天和最后一天
    first_day = datetime(target_year, target_month, 1)
    if target_month == 12:
        last_day = datetime(target_year + 1, 1, 1) - timedelta(days=1)
    else:
        last_day = datetime(target_year, target_month + 1, 1) - timedelta(days=1)

    # 生成整月所有日期的列表(仅保留日期部分)
    date_list = []
    current_day = first_day
    while current_day <= last_day:
        date_list.append(current_day.date())
        current_day += timedelta(days=1)

    # 查询该月销售记录,构建日期-状态映射字典
    sale_records = SaleDates.objects.filter(
        date_of_sale__year=target_year,
        date_of_sale__month=target_month
    )
    sale_status_map = {}
    for record in sale_records:
        sale_date = record.date_of_sale.date()
        sale_status_map[sale_date] = record.sold_status

    # 传递数据到模板
    context = {
        'date_list': date_list,
        'sale_status_map': sale_status_map,
        'target_year': target_year,
        'target_month': target_month
    }
    return render(request, 'template.html', context)

template.html 代码实现

<div>
    <h3>{{ target_year }}年{{ target_month }}月销售日历</h3>
    <table class="table table-hover table-bordered">
        <tr>
            <th>序号</th>
            <th>日期</th>
            <th>销售状态</th>
        </tr>
        {% for date in date_list %}
        <tr>
            <td>{{ forloop.counter }}</td>
            <td>{{ date }}</td>
            <td>{{ sale_status_map.get(date, '') }}</td>
        </tr>
        {% endfor %}
    </table>
</div>

补充说明

  • 视图通过日期计算确保覆盖目标月份的每一天,不会遗漏无销售记录的日期
  • 使用字典映射销售状态,模板中通过get方法快速匹配,无对应记录时返回空字符串
  • 如需指定特定年月,可修改视图逻辑,从URL参数或表单中获取目标年份和月份

内容的提问来源于stack exchange,提问作者JTO IT CDR

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 10:11:04