Django调度,如何检查日期是否在两个日期之间

Django scheduling, how to check if date is between two dates

目前我正在进行另一个预订项目。这是我的预订模型:

class Reservation(models.Model):
    user = models.ForeignKey(User, null = True, blank = True)
    employee = models.ForeignKey(Employee)
    service = models.ForeignKey(Service)
    starttime = models.DateTimeField('reservation start')
    endtime = models.DateTimeField('reservation end')

    def __unicode__(self):
        return u"Nr: %s" % self.id

我认为我的应用程序应该这样工作 - 用户选择员工。用户选择服务(持续时间取决于具体服务)。然后用户在日历上选择日期。现在,如果所选员工有空,日期将传递给每隔 30 分钟检查一次的方法。然后显示所有可用的预订时间。例如:

Employee choice:
John Doe
Service choice:
Air Filter Replacement
Duration: 1 hour
Date picked:
30/06/2016
Available reservation time:
12:30 - 13:30
15:30 - 16:30 
17:00 - 18:00

Employee choice:
John Doe
Service choice:
Suction Manifold Flaps Removal
Duration: 2 hours
Date picked:
1/07/2016
Available reservation time:
13:00 - 15:00 
17:00 - 19:00

这对我来说是一个巨大的障碍,因为我不知道如何处理这个问题。

我的第一个想法是,我可以获取用户选择的日期、员工 ID、持续时间,并在 while 循环中每 30 分钟迭代一次工作时间:

time_interval = 30  #interval
working_day_start = 10  #starts working at 10 am
working_day_end = 20    #ends working at 8 pm
duration = service_duration  #how long service takes
start = choosen_date + datetime.timedelta(hours = working_day_start)
end = choosen_date + datetime.timedelta(hours = working_day_end)
availibility_table = []

while start <= end – datetime.timedelta(hours = duration):
    is_available = employee.isAvailable(start, employee_id, duration)
    if is_available:
        availibility_date = [start, start + datetime.timedelta(hours = duration)]
        availibility_table.append(availibility_date)
    start += datetime.timedelta(minutes = time_interval)
return availability_table

如您所见,我需要 employee.isAvailable 函数,但我不知道如何编写它。基本上它必须告诉我是否在开始和开始+持续时间之间的时间说员工已经被分配到任何预订。

另外,该方法是否正确且最佳?有没有更简单的方法来实现我所需要的?

编辑:

这是我的员工模型。就这么简单。

class Employee(models.Model):
    first_name = models.CharField(max_length = 30, blank = False)
    last_name = models.CharField(max_length = 30, blank = False)

    def __unicode__(self):
        return self.first_name + ' ' + self.last_name

这应该有效:

def isAvailable(start, employee_id, duration):
    employee = Employee.objects.get(pk=employee_id)
    # See if the employee has any reservations that overlap
    # with this window. The logic here is that the *start* of
    # the reservation is before the *end* of the time period we
    # are checking, and the *end* of the reservation is after the
    # *start* of the time period we are checking.
    this_period_end = start + datetime.timedelta(hours=duration)
    existing_reservations = employee.reservation_set.filter(
        starttime__lte=this_period_end,
        endtime__gte=start
    )

    # If we found matches, then the employee is busy for some part of
    # this period
    return not existing_reservations.exists()

它确实意味着对您要测试的每个时间段进行查询。从概念上讲,我觉得必须有一个更有效的解决方案,但目前我还没有解决。无论如何,一旦您确认此逻辑有效,您应该能够对其进行细化。