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

后端 未结 7 1609
执念已碎
执念已碎 2020-11-22 16:02

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 obje

7条回答
  •  不知归路
    2020-11-22 16:31

    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).

提交回复
热议问题