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

Django中如何从考勤数据表中查询获取不重复的日期数据

解决方案

方案1:视图层处理(推荐,数据库层面去重效率更高)

1. 修改views.py代码

直接通过Django ORM在查询时就获取去重后的日期,修改后的index函数如下:

def index(request):
    staffs = staff.objects.all()
    attendances = attendance.objects.all()
    date = datetime.date.today()
    # 新增:查询所有不重复的考勤日期,按日期升序排列
    unique_attendance_dates = attendance.objects.values_list('date', flat=True).distinct().order_by('date')

    return render(request, "salary/index.html", {
        'staff': staffs, 
        'attendance': attendances, 
        'date': date,
        # 把去重后的日期列表传到模板
        'unique_dates': unique_attendance_dates
    })

这里的values_list('date', flat=True)会直接返回仅包含date字段值的一维列表,distinct()实现去重,order_by('date')保证日期按先后顺序排列。

2. 修改模板代码

把原来的日期遍历部分替换为遍历去重后的日期列表即可:

{% for date in unique_dates %}
    <th>{{ date }}</th>
{% endfor %}

方案2:模板层直接处理(仅适合小数据量场景)

如果不想修改视图代码,也可以用Django模板自带的{% ifchanged %}标签实现去重,修改模板代码如下:

{% for attendances in attendance %}
    {% ifchanged attendances.date %}
        <th>{{ attendances.date }}</th>
    {% endifchanged %}
{% endfor %}

该方法会在遍历考勤记录时,只输出和上一条记录日期不同的内容,实现去重效果,但数据量较大时效率低于方案1。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 23:27:03