Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering on Dates for Availability in Django

Imagine a hostel keeping track of whether or not a room is available on any given night. In addition, if a party of more than 1 guest is looking for a room, they will only want a room with at least that many beds available.

Given a date range, I would like to find rooms that are available and have at least the number of beds as there are guests (along with other filtering).

How can I go about that without effectively chaining ANDs with .filters? (Which is how it works now - and is making my database very sad.)

I'm certainly open to a different scheme for storing the availability data if needed too.

Thanks! (Hypothetical classes below to give a better sense of the problem.)

class Room(models.Model):
    name = models.CharField(max_length=100)

class RoomAvailability(models.Model):
    room = models.ForeignKey(Rooms)
    date = models.DateField()
    beds = models.IntegerField(default=1)
like image 669
philipk Avatar asked Mar 15 '26 01:03

philipk


1 Answers

available_rooms = (Room.objects
    .filter(roomavailability__date__range=(start_date, end_date))
    .values('roomavailability__date', 'pk')
    .annotate(sum=Sum('roomavailability__beds'))
    .filter(sum__gte=min_beds))

Update: forgot that we need room availability per day. This query will return sets of dates available and their room PK.

like image 178
Yuji 'Tomita' Tomita Avatar answered Mar 17 '26 16:03

Yuji 'Tomita' Tomita



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!