如何在 Django 中按日期范围过滤查询对象?

编程入门 行业动态 更新时间:2024-10-25 16:25:19
本文介绍了如何在 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-2011 和 31-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 中按日期范围过滤查询对象?

本文发布于:2023-10-28 23:15:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1538048.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   按日   如何在   Django

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!