philipk
philipk

Reputation: 1483

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)

Upvotes: 3

Views: 372

Answers (1)

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.

Upvotes: 1

Related Questions