Question

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

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top