Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 384
Synthead Avatar asked Jun 10 '14 05:06

Synthead


2 Answers

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.

like image 172
Lutz Prechelt Avatar answered Nov 08 '22 00:11

Lutz Prechelt


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.

like image 28
ruddra Avatar answered Nov 08 '22 02:11

ruddra