1

I have a model

class Booked(models.Model):
    start_date_time = models.DateTimeField()
    end_date_time = models.DateTimeField()
    resource = models.ForeignKey(Resouce)

How do I check if a particular datetime range doesn't fall between the start or end datetimes of any of the booked objects?

I want to check if I can book a resource with say book_start_date and book_end_date without it being already booked during that range

blue_zinc
  • 2,410
  • 4
  • 30
  • 38

1 Answers1

3

Use __lte and __gte with exists() to check if there is something in the date range:

Booked.objects.exists(start_date_time__lte=book_end_date, 
                      end_date_time__gte=book_start_date)

See also: Determine Whether Two Date Ranges Overlap.

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • You can use __range either: http://stackoverflow.com/questions/4668619/django-database-query-how-to-filter-objects-by-date-range – dfranca May 13 '14 at 02:39