Django 检查时间是否在对象的时间域范围内

Django check if time is in an object's timefield range

如何检查时间是否在两个时间域的范围内?

#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和end_time是在创建对象后计算的,因为它需要一个多对多字段的属性

在我的视图中,我想检查是否存在一个对象

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

如何检查它的时间是否在两个时间域之间?

编辑: 环顾四周这些问题有点帮助

Django After Midnight Business Hours TimeField Comparison Error

目前我正在尝试的方法是

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

这一行没有返回我要找的东西,我不确定我哪里出错了

这不是一个很好的解决方案,但最终它会起作用

这个答案解决了我的问题

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