如何在 Django 中按日期范围过滤查询对象? [英] How do I filter query objects by date range in Django?

查看:41
本文介绍了如何在 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.

如何过滤日期在 1-Jan-201131-Jan-2011 之间的所有对象?

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

推荐答案

使用

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

编辑

正如 Bernhard Vallant 所说,如果您想要一个排除指定范围结束的查询集,您应该考虑他的解决方案,它利用了 gt/lt(大于/小于).

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

这篇关于如何在 Django 中按日期范围过滤查询对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆