首页 > 解决方案 > 如何在 django 中检索不同类型的数据?

问题描述

我创建了一个考勤管理系统,我想从表中检索不同类型的日期。喜欢,

在我的出勤表中,有不同的日期,但某些日期重复前 - 对于每个日期,有多少用户有出勤

staff table.                attendance table

id = 1                      id = 1
name = john                 staff_id = 1
                            date = 31.08.2021
id = 2                      attendance = present
name = harry 
                            id = 2
                            staff_id = 2
                            date = 31.08.2021
                            attendance = absent

                            id = 3
                            staff_id = 1
                            date = 01.09.2021
                            attendance = present

                            id = 4
                            staff_id = 2
                            date = 01.09.2021
                            attendance = present

从上表数据中我想检索唯一的日期而不重复

所以当我们编写代码时,答案将是

31.08.2021
01.09.2021

这是我的模板文件

{% for attendances in attendance %}
    <th>{{ attendances.date }}</th>
    // here i want to retrive 31.08.2021 and 01.09.2021
{% endfor %}

这是我的意见文件

def index(request):
    staffs = staff.objects.all()
    attendances = attendance.objects.all()
    date = datetime.date.today()

    return render(request, "salary/index.html", {'staff': staffs, 'attendance': attendances, 'date': date})

标签: djangodjango-views

解决方案


您可以直接从数据库中获取它(如果您使用的是 postgres),或者自己从attendances. 只做对你最好的事。

def index(request):
    staffs = staff.objects.all()
    attendances = attendance.objects.all()
    date = datetime.date.today()
    
    
    # unique_dates = list(attendance.objects.all().order_by().values('date').distinct())
    # OR
    # unique_dates = list({a.date for a in atteendances})
    

    return render(request, "salary/index.html", {'staff': staffs, 'attendance': attendances, 'date': date, 'unique_dates': unique_dates})

推荐阅读