问题
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:
Djangoprovides 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