问题:使用Django在两个日期之间选择

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

我知道如何使用原始SQL轻松做到这一点,但是如何使用Django ORM做到这一点呢?

这是我要在查询中添加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')

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

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

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

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

回答 0

使用__range运算符:

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

Use the __range operator:

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

回答 1


回答 2

两种方法

.filter(created_at__range=[from_date, to_date])

另一种方法

.filter(Q(created_at__gte=from_date)&Q(created_at__lte=to_date))
  • gte意味着大于等于
  • 小于等于

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

回答 3

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

您需要将值转换为日期:

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

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

You need to casts the value as date:

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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。