我有一个简单的约会应用,可让用户注册未填写的时间段。用户将选择一个日期,并在数据库中查询当天可用的时隙。我将如何查询以获取仍可用的时隙?
models.py
class Appointment(models.Model):
TIMESLOT_LIST = (
(1, '10:00 – 11:00'),
(2, '11:00 – 12:00'),
(3, '12:00 – 13:00'),
(4, '13:00 – 14:00'),
(5, '14:00 – 15:00'),
(6, '15:00 – 16:00'),
(7, '16:00 – 17:00'),
(8, '17:00 – 18:00'),
(8, '18:00 – 19:00'),
)
date = models.DateField(default=date.today)
timeslot = models.IntegerField(choices=TIMESLOT_LIST, null=True)
views.py
def make_appointment(request):
all_appointments = Appointment.objects.values_list('timeslot')
appointments = Appointment.objects.filter(user=request.user)
data_input = request.GET.get('date')
available_appointments = Appointment.objects.filter(
date = data_input
).exclude(timeslot = appointments).values_list(
'timeslot'
).order_by('timeslot')
return TemplateResponse(
request,
'scheduling/appointment.html',
{
"appointments" : appointments,
"all_appointments" : all_appointments,
"data_input": data_input
}
)
答案 0 :(得分:2)
您可以这样做来形成可用时间的新列表;
available_appointments = [
(value, time) for value, time in TIMESLOT_LIST if value not in all_appointments
]
或者如果您想要一个元组;
tuple(
(value, time) for value, time in TIMESLOT_LIST if value not in all_appointments
)
然后您可以在模板中提供这些选择,以供人们选择。
终端提供的示例;
>>> [(value, time) for value, time in TIMESLOT_LIST if value not in [1, 2, 3]]
[(4, '13:00 – 14:00'), (5, '14:00 – 15:00'), (6, '15:00 – 16:00'), (7, '16:00 – 17:00'), (8, '17:00 – 18:00'), (8, '18:00 – 19:00')]