Reputation: 27
I have a simple appointment app that lets users sign up for unfilled timeslots. The user would select a date and query the database for timeslots that are available for that day. How would I make a query to get timeslots that are still available?
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
}
)
Upvotes: 0
Views: 219
Reputation: 12849
You could form a new list of the available times by doing;
available_appointments = [
(value, time) for value, time in TIMESLOT_LIST if value not in all_appointments
]
Or if you want a tuple;
tuple(
(value, time) for value, time in TIMESLOT_LIST if value not in all_appointments
)
You could then offer those choices in the template for people to choose from.
An example from the terminal;
>>> [(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')]
Upvotes: 2