2016-06-18 2 views
1

현재 다른 예약 프로젝트를 진행 중입니다. 내 예약 모델은 다음과 같습니다.Django 스케줄링, 날짜가 두 날짜 사이에 있는지 확인하는 방법

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 

이 나를 위해 큰 장애물이다.

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 

당신은 내가 직원이 필요할 것 볼 수 있듯이 :

내 첫번째 생각은 내가 while 루프에서 매 30 분마다 사용자가 선택한 날짜, 직원 ID, 기간을 가지고 근무 시간을 반복 할 수 있었다. 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 
+0

게시물에'Employee' 스키마를 추가 할 수 있습니까? 도움이 될 수 있습니다. – oxalorg

+0

@MiteshNinja Employee 모델을 추가했습니다. 가능한 한 간단합니다. – Kesto

답변

1

이 작동합니다 :

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

그것은 테스트 할 모든 기간에 대한 쿼리를 수행 의미한다. 개념적으로는보다 효율적인 솔루션이 있어야하지만 지금은 나를 벗어날 수있는 것처럼 느껴집니다. 어떤 경우이 논리가 작동하는지 확인한 후에는이를 수정할 수 있어야합니다.

+0

작동하는 것처럼 보이지만 분명히 lt와 gt에 lte 및 gte 연산자를 변경해야했습니다. 그렇지 않으면 30 분의 오프셋이있었습니다. 중대한 응답 나는 진짜로 당신의 도움을 평가한다! – Kesto

관련 문제