Kihaf
Kihaf

Reputation: 77

Django ORM query on fk set

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

Upvotes: 1

Views: 57

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476750

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.

Upvotes: 1

Related Questions