Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I filter query objects by date range in Django?

I've got a field in one model like:

class Sample(models.Model):     date = fields.DateField(auto_now=False) 

Now, I need to filter the objects by a date range.

How do I filter all the objects that have a date between 1-Jan-2011 and 31-Jan-2011?

like image 324
user469652 Avatar asked Jan 12 '11 12:01

user469652


1 Answers

Use

Sample.objects.filter(date__range=["2011-01-01", "2011-01-31"]) 

Or if you are just trying to filter month wise:

Sample.objects.filter(date__year='2011',                        date__month='01') 

Edit

As Bernhard Vallant said, if you want a queryset which excludes the specified range ends you should consider his solution, which utilizes gt/lt (greater-than/less-than).

like image 142
crodjer Avatar answered Oct 25 '22 12:10

crodjer