gordon33 gordon33 - 1 year ago 80
Python Question

Django: Filter objects by date range

My object model is :

class Event(models.Model):
start = models.DateTimeField()
end = models.DateTimeField()

I need to filter all objects for today.

I have one object with start date 2014/03/01 00:00 and end date 2014/10/01 00:00.
I need to have this object when filtering objects by today date ex.:

Event.objects.filter(start__gte=today, end__lte=today)

How can I filter objects by today date and get all results where start > today < end ?

Answer Source

Get the today's date from datetime.date.today() and use gt and lt:

import datetime

today = datetime.date.today()
Event.objects.filter(start__lt=today, end__gt=today)

This would filter objects where start date is less than today and end date is greater than today.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download