简体   繁体   中英

Django: DateTime query

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM