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

时间:2016-06-18 15:31:16

标签: django date schedule

目前我正在开展另一个预订项目。这是我的预订模式:

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

1 个答案:

答案 0 :(得分:2)

这应该有效:

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

这意味着对您要测试的每个时段执行查询。从概念上讲,我觉得必须有一个更有效的解决方案,但目前我无法解决。在任何情况下,一旦确认此逻辑有效,您应该能够对其进行优化。