I am building a django query to make apartment reservations. User enters start and end date and the db is checked too see if a clashing reservation already exists. That is to say, if any part of the daterange of the reservation overlaps with an existing reservation’s daterange.
I have a system that works, but it hits the DB 3 times, and I’m sure it could be done in 1 (with OR condition in the query?). Can I optimise the following?:
bookings = Booking.objects.filter( arrival_date__range=(query_start, query_end) )
if len(bookings) > 0:
status = 'failure'
else:
bookings = Booking.objects.filter( departure_date__range=(query_start, query_end) )
if len(bookings) > 0:
status = 'failure'
else:
bookings = Booking.objects.filter( arrival_date__lte=query_start ).filter( departure_date__gte = query_end )
if len(bookings) > 0:
status = 'failure'
Many thanks for feedback
This is possible by ORing querysets and using th Q object, with something like this:
This should only hit the db once.