目前我正在开展另一个预订项目。这是我的预订模型:
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()
这确实意味着对您想要测试的每个时期进行查询。从概念上讲,我觉得必须有一个更有效的解决方案,但目前我还没有找到。无论如何,一旦确认此逻辑有效,您就应该能够对其进行改进。
关于Django调度,如何检查日期是否在两个日期之间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37898651/