新版本的 Django 中 DateModifierNode 的替代品是什么

What is the replacement for DateModifierNode in new versions of Django

我想根据模型的两个字段进行查询,一个日期,一个int偏移量,用作timedelta

model.objects.filter(last_date__gte=datetime.now()-timedelta(days=F('interval')))

不行,因为不能将 F() 表达式传递到 timedelta

稍微挖掘一下,我发现了 DateModifierNode - 尽管它似乎已在此提交中删除:https://github.com/django/django/commit/cbb5cdd155668ba771cad6b975676d3b20fed37b (from this now-outdated SO question Django: Using F arguments in datetime.timedelta inside a query)

提交提到:

The .dates() queries were implemented by using custom Query, QuerySet, and Compiler classes. Instead implement them by using expressions and database converters APIs.

这听起来很明智,而且应该仍然有一个简单快捷的方法 - 但我一直在寻找如何做到这一点但毫无结果 - 有人知道答案吗?

啊,来自文档的回答:https://docs.djangoproject.com/en/1.9/ref/models/expressions/#using-f-with-annotations

from django.db.models import DateTimeField, ExpressionWrapper, F

Ticket.objects.annotate(
    expires=ExpressionWrapper(
        F('active_at') + F('duration'), output_field=DateTimeField()))

这应该使我的原始查询看起来像

model.objects.annotate(new_date=ExpressionWrapper(F('last_date') + F('interval'), output_field=DateTimeField())).filter(new_date__gte=datetime.now())

在 Django 1.10 中,有更简单的方法来执行此操作,但您需要稍微更改模型:使用 DurationField。我的模型如下:

class MyModel(models.Model):

    timeout = models.DurationField(default=86400 * 7)  # default: week
    last = models.DateTimeField(auto_now_add=True)

查找 last 之前 now 减去 timeout 的对象的查询是:

MyModel.objects.filter(last__lt=datetime.datetime.now()-F('timeout'))