问题描述
我想根据一个模型的两个字段做一个查询,一个日期,一个 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(来自这个现已过时的问题 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.
这听起来很明智,而且仍然应该有一种快速简便的方法 - 但我一直在寻找如何做到这一点太久没有结果 - 有谁知道答案吗?
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
在 now
减去 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 的替代品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!