Django: Using F arguments in datetime.timedelta inside a query

强颜欢笑 提交于 2019-11-26 21:37:17

问题


Using Django model syntax, if I do this:

ThatModel.objects.filter(
    last_datetime__lte=now + datetime.timedelta(seconds=F("interval")))

I get:

TypeError: unsupported type for timedelta days component: ExpressionNode

Is there a way to make this work with pure Django syntax (and not parsing all the results with Python)?


回答1:


From django docs:

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.

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

For your solution, you can check this: DateModifierNode, or just save the value of interval elsewhere and then pass it as parameter of timedelta.




回答2:


Just avoid timedelta's F-ignorance

filter knows about F, but timedelta does not. The trick is to keep the F out of the timedelta argument list:

ThatModel.objects.filter(
    last_datetime__lte=now + datetime.timedelta(seconds=1)*F("interval"))

This will work with PostgreSQL, but, alas, not with SQlite.



来源:https://stackoverflow.com/questions/24133829/django-using-f-arguments-in-datetime-timedelta-inside-a-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!