Django проверяет, находится ли время в диапазоне временных полей объекта

Как проверить, находится ли время в диапазоне двух временных полей?

#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)

Общее_время и конечное_время вычисляются после создания объекта, поскольку для этого требуется атрибут из поля "многие ко многим"

В моем представлении, где я хочу проверить, существует ли объект

#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')

Как он может проверить, попадает ли его время между двумя временными полями?

Это не очень красивое решение, но в конце концов оно работает

этот ответ решил мой вопрос

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):
Вернуться на верх