Python 使用 Django 在两个日期之间进行选择

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3963201/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:35:02  来源:igfitidea点击:

Select between two dates with Django

pythondjango

提问by Jeff Taggarty

I am looking to make a query that selects between dates with Django.

我正在寻找一个查询,在 Django 的日期之间进行选择。

I know how to do this with raw SQL pretty easily, but how could this be achieved using the Django ORM?

我知道如何使用原始 SQL 很容易地做到这一点,但是如何使用 Django ORM 实现这一点?

This is where I want to add the between dates of 30 days in my query:

这是我想在查询中添加 30 天之间的日期的地方:

start_date = datetime.datetime.now() + datetime.timedelta(-30)
context[self.varname] = self.model._default_manager.filter(
    current_issue__isnull=True
    ).live().order_by('-created_at')

采纳答案by Daniel Roseman

Use the __rangeoperator:

使用__range运算符:

...filter(current_issue__isnull=True, created_at__range=(start_date, end_date))

回答by Ignacio Vazquez-Abrams

回答by Manjuanth V M

two methods

两种方法

.filter(created_at__range=[from_date, to_date])

another method

另一种方法

.filter(Q(created_at__gte=from_date)&Q(created_at__lte=to_date))
  • gte means greater than equal
  • lte means less than equal
  • gte 表示大于等于
  • lte 表示小于等于

回答by suhailvs

If you are using a DateTimeField, Filtering with dates won't include items on the last day.

如果您使用的是DateTimeField,则使用日期过滤将不包括最后一天的项目。

You need to casts the value as date:

您需要将值转换为日期:

...filter(created_at__date__range=(start_date, end_date))