Django:在查询中的 datetime.timedelta 中使用 F 参数 [英] Django: Using F arguments in datetime.timedelta inside a query
问题描述
使用 Django 模型语法,如果我这样做:
Using Django model syntax, if I do this:
ThatModel.objects.filter(
last_datetime__lte=now + datetime.timedelta(seconds=F("interval")))
我明白了:
TypeError: unsupported type for timedelta days component: ExpressionNode
有没有办法用纯 Django 语法(而不是用 Python 解析所有结果)来完成这项工作?
Is there a way to make this work with pure Django syntax (and not parsing all the results with Python)?
推荐答案
来自 django 文档:
From django docs:
Django
提供了 F 表达式来允许这样的比较.实例F() 充当对查询中模型字段的引用.这些然后可以在查询过滤器中使用引用来比较同一模型实例上的两个不同字段.
Django
provides F expressions to allow such comparisons. Instances of F() act as a reference to a model field within a query. These references can then be used in query filters to compare the values of two different fields on the same model instance.
这意味着您可以使用 F()
在查询中进行比较.F()
返回引用,因此当您将其用作 timedelta
对象的参数时,您会收到错误 ExpressionNode
.您可以查看文档.您可以查看F()一个>
That means you can use F()
for comparing within queries. F()
returns reference so when you use it as parameter for timedelta
object, you get the error ExpressionNode
. You can check the documentation. You might check the source code of F()
对于您的解决方案,您可以查看:DateModifierNode,或者只是将interval
的值保存在别处,然后作为timedelta
的参数传递.
For your solution, you can check this: DateModifierNode, or just save the value of interval
elsewhere and then pass it as parameter of timedelta
.
这篇关于Django:在查询中的 datetime.timedelta 中使用 F 参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!