1

I have a problem with lookup that looks for a value in related set.

class Room(models.Model):
    name = models.Charfield(max_lentgh=64)

class Availability(models.Model):
    date = models.DateField()
    closed = models.BooleanField(default=False)
    room = models.ForeignKey(Room)

Considering that there is one availability for every date in a year. How can use ORM query to find whether room withing given daterange (i.e. 7 days) has:

  1. availability exist for every day within given daterange
  2. none of the availabilities has closed=True

I was unable to find any orm examples that check whether all objects within daterange exist

Kihaf
  • 65
  • 1
  • 4

1 Answers1

1

You can enumerate over the dates, and ensure that it has for that date an Availability with closed=False:

from datetime import date, timedelta

rooms = Room.objects.all()
start_date = date(2022, 7, 21)  # first day
for dd in range(7):             # number of days
    dt = start_date + timedelta(days=dd)
    rooms = rooms.filter(availability__date=dt, availability__closed=False)

The rooms will after the for loop have a QuerySet with all Rooms that have for all dates in that range Availability objects with closed=False.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • thanks! but is it possible to do it in single orm query without reverting to raw sql? – Kihaf Jul 21 '22 at 20:48
  • @Kihaf: this will make a *single* SQL query: querysets are lazy. The filters are *not* performed incrementally, it simply builds up a query that will then evaluated once if you "consume" `rooms`. – Willem Van Onsem Jul 21 '22 at 20:50