【问题标题】:Django - Show dates of appointmentsDjango - 显示约会日期
【发布时间】:2022-01-01 01:37:54
【问题描述】:

我想在模板中显示未预订约会的日期。出于这个原因,我到目前为止:

# Collect only the dates so that i can find what is not in that range.
example_dates = Appointment.objects.values_list('start_appointment', flat=True)

# Initialize start and end date
start_date = datetime.date.today()
end_date = start_date + datetime.timedelta(days=5)

# Initialize new list that will include records does not exists
not_found_dates = []

# Loop through in date range and if date does not exists 
# Create a dict and add it to the list
for n in range(int((end_date - start_date).days)):
    new_date = start_date + datetime.timedelta(days=n)
    if new_date not in not_found_dates:
        not_found_dates.append(new_date)
        print(new_date)

# Get original queryset
examples = Appointment.objects.filter(start_appointment__range=(start_date, end_date)).values('start_appointment')
print(examples)

# Convert it to a list
examples = list(examples)

return render(request, 'appointments/add-appointment.html', {'examples': examples, 'not_found_dates': not_found_dates})

当我从循环中打印 new_date 时,我得到: 2021-11-22 2021-11-23 2021-11-24 2021-11-25 2021-11-26

来自examples 的查询返回我在 2021 年 11 月 23 日(2)和 2021 年 11 月 22 日(1)范围内的 db 中有 3 个约会。

是否可以显示未预订的约会日期,即2021-11-24、2021-11-25、2021-11-26。

【问题讨论】:

    标签: django list loops datetime django-queryset


    【解决方案1】:

    您将获得定义时间范围内的日期列表(持续时间为 num_days),其中包含不属于查询的日期:

    from datetime import date, timedelta
    
    num_days = 5
    start_date = date.today()
    timeframe = [start_date + timedelta(days=d) for d in range(num_days)]
    exclude = list(Transaction.objects.values_list("start_appointment", flat=True).distinct())
    
    set(timeframe) - set(exclude)
    

    【讨论】:

    • 感谢您的帮助,但这不是我想要的。我想显示 num_days 中没有约会的日期。这显示了 num_days 内的约会,不包括其余的约会。
    • 不,恰恰相反。它应该是你需要的。它不包括给定时间范围内的约会日期。所以现在你得到了所有可用的日子。
    • 是的,我确定。似乎您将日期时间存储在模型中,而不仅仅是日期。在帖子开头有这样的信息会很好。您可以将查询更改为使用"start_appointment__date"。这将返回日期而不是日期时间。
    • 你是对的伙伴!很抱歉没有做对。感谢您的帮助。
    猜你喜欢
    • 2022-01-12
    • 1970-01-01
    • 2016-03-24
    • 2013-10-31
    • 1970-01-01
    • 2017-05-12
    • 1970-01-01
    • 2014-03-15
    • 2012-10-02
    相关资源
    最近更新 更多