在Django新版本中替换DateModifierNode是什么 [英] What is the replacement for DateModifierNode in new versions of Django
问题描述
我想基于模型的两个字段执行查询,日期,由int的偏移量,用作timedelta
I want to do a query based on two fields of a model, a date, offset by an int, used as a timedelta
model.objects.filter(last_date__gte=datetime.now()-timedelta(days=F('interval')))
是一个不要去,因为F()表达式不能传递给timedelta
is a no-go, as a F() expression cannot be passed into a timedelta
有一点挖掘,我发现 DateModifierNode
- 虽然它似乎在此提交中被删除: https://github.com/django/django/commit/cbb5cdd155668ba771cad6b975676d3b20fed37b (从这个现在过时的SO问题 Django:在查询中的datetime.timedelta中使用F参数)
A little digging, and I discovered DateModifierNode
- though it seems it was removed in this commit: https://github.com/django/django/commit/cbb5cdd155668ba771cad6b975676d3b20fed37b (from this now-outdated SO question Django: Using F arguments in datetime.timedelta inside a query)
提交提到:
.dates()查询我们通过使用自定义Query,QuerySet,
和编译器类来实现。而是通过使用表达式和
数据库转换器API实现它们。
The .dates() queries were implemented by using custom Query, QuerySet, and Compiler classes. Instead implement them by using expressions and database converters APIs.
这听起来很合理,就像应该还要快一点简单的方法 - 但是我一直在无尽地寻找如何做到这一点太长时间 - 任何人都知道答案?
which sounds sensible, and like there should still be a quick easy way - but I've been fruitlessly looking for how to do that for a little too long - anyone know the answer?
推荐答案
在Django 1.10中有一个比较简单的方法,但是您需要更改一些模型:使用DurationField。我的模型如下:
In Django 1.10 there's simpler method to do it but you need to change the model a little: use a DurationField. My model is as follows:
class MyModel(models.Model):
timeout = models.DurationField(default=86400 * 7) # default: week
last = models.DateTimeField(auto_now_add=True)
,查找 last
之前的对象在之前
减去$ code> timeout 是:
and the query to find objects where last
was before now
minus timeout
is:
MyModel.objects.filter(last__lt=datetime.datetime.now()-F('timeout'))
这篇关于在Django新版本中替换DateModifierNode是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!