How do I check if a time is in the range of two timefields?
#appointmentApp.models Appointment
#Appointments
class Appointment(models.Model):
...
date_selected = models.DateField(blank=True, default='2001-12-1')
time_start = models.TimeField(blank=True)
total_time = models.IntegerField(blank=False, null=False, default=0)
end_time = models.TimeField(blank=True, null=True)
appointment_accepted = models.BooleanField(blank=False, default=False)
Total_time and end_time are calculated after the object is created because it requires an attribute from a many to many field
In my views where I want to check if there is an object that exists
#appointmentApp.views def appointment_view
def appointment_view(request):
...
#form is submitted
else:
form = AppointmentForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
date = cd.get('date_selected') #this is a datetime field
start = cd.get('time_start')
#appointments = Appointment.objects.filter(date_selected=date, start_time__range=())
#form needs to save first because total time and end time don't have values until after the object is saved
form.save()
new_appointment = Appointment.objects.filter(date_selected=date, time_start=start, appointment_accepted=False)
for apps in new_appointment:
new_app_starttime = apps.time_start
new_app_endtime = apps.end_time
appointments = Appointment.objects.filter(date_selected=date, appointment_accepted=True)
#if the start time
#my question is here
for app in appointments:
if app.time_start__range(new_app_starttime, new_app_endtime):
print('another appointment begins/ends during this time slot!')
return render(request, 'home.html')
How can it check if its time falls in between two timefields?
Edit: Been looking around these question have been a bit helpful
Django filter when current time falls between two TimeField values
Django After Midnight Business Hours TimeField Comparison Error
the current method I am trying is
#appointmentApp.views appointment_view
if Appointment.objects.filter(date_selected=date, time_start__lte=F('end_time')).exists():
print('Y E S')
Appointment.objects.filter(date_selected=date, time_start=start, appointment_accepted=False).delete()
This line hasn't returned what I am looking for and Im not sure where Im going wrong with it
Its not a pretty solution but at the end of the day it works
this answer solved my question
https://stackoverflow.com/a/65572546/10485812
#gets the appointment that is being checked
n_a = Appointment.objects.get(date_selected=date, time_start=start, appointment_accepted=False)
#filters for all appointments that have been accepted and share the same date as n_a
appointments = Appointment.objects.filter(date_selected=date, appointment_accepted=True)
#checks each appointment on that day and sees if the times overlap
for apps in appointments:
if (apps.time_start < n_a.time_start < apps.end_time) or (apps.time_start < n_a.end_time < apps.end_time) or (n_a.time_start <= apps.time_start and n_a.end_time >= apps.end_time):