已将条件换换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
哎呀,我觉得这会打破重叠。我已添加更新 –