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

2👍

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.

👤ruddra

44👍

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.

Leave a comment