已將條件換換gte <> lte
。第二個查詢起作用,因爲的匹配日期爲hotelrooms_id=1
。
但要檢查是否start_date
和end_date
在有效範圍內checkin_booked_date
到checkout_booked_date
:
check_for_bookings = HotelCalendar.objects.filter(checkin_booked_date__lte=start_date,
checkout_booked_date__gte=end_date,
hotelrooms_id=1)
使用exists
,如果你只需要檢查,而不是獲取對象:
if HotelCalendar.objects.filter(checkin_booked_date__lte=start_date,
checkout_booked_date__gte=end_date,
hotelrooms_id=1).exists():
更新:
從這個SO answer,我們可以知道,如果開始和結束日期與客戶端佔用的日期重疊:
from datetime import datetime as dt
hotelcalendar = HotelCalendar.objects.filter(hotelrooms_id=1)
start_date = dt.strptime(start_date, '%Y-%m-%d')
end_date = dt.strptime(end_date, '%Y-%m-%d')
if hotelcalendar.checkin_booked_date <= end_date and hotelcalendar.checkout_booked_date >= start_date:
print "not available"
else:
print "available"
更新:
我調整這樣說:我改變了「過濾器'到'get',因爲它會返回'AttributeError'。我直接使用datetime.date()
。到目前爲止它工作得很好!
>>> import datetime
>>> hotelcalendar= HotelCalendar.objects.get(hotelrooms_id=1)
>>> start_date= datetime.date(2016, 06, 14)
>>> end_date= datetime.date(2016, 06, 19)
>>> if hotelcalendar.checkin_booked_date <= end_date and hotelcalendar.checkout_booked_date >= start_date:
... print 'not available'
... else:
... print 'available'
...
not available
>>> hotelcalendar= HotelCalendar.objects.get(hotelrooms_id=1)
>>> start_date= datetime.date(2016, 06, 15)
>>> end_date= datetime.date(2016, 06, 19)
>>> if hotelcalendar.checkin_booked_date <= end_date and hotelcalendar.checkout_booked_date >= start_date:
... print 'not available'
... else:
... print 'available'
...
available
>>> hotelcalendar= HotelCalendar.objects.get(hotelrooms_id=3)
>>> start_date= datetime.date(2016, 06, 02)
>>> end_date= datetime.date(2016, 06, 10)
>>> if hotelcalendar.checkin_booked_date <= end_date and hotelcalendar.checkout_booked_date >= start_date:
... print 'not available'
... else:
... print 'available'
...
not available
>>>
感謝您的答覆bro ..它的工作,但是當我設置start_date ='2016-06-14'和end_date ='2016-06-19',我得到'可用'。我認爲它應該是'不可用',因爲'start_date ='2016-06-14'已經在日曆中保存爲hotelout的checkout_date。您怎麼看? – YoYo
即使對於hotelroom_id 3,當我選擇start_date ='2016-06-02',end_date ='2016-06-10'我就可以預訂,而且不應該這樣。你怎麼看? – YoYo
哎呀,我覺得這會打破重疊。我已添加更新 –