18

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

Synthead
  • 2,162
  • 5
  • 22
  • 25

2 Answers2

42

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.

Lutz Prechelt
  • 36,608
  • 11
  • 63
  • 88
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
  • 50,746
  • 7
  • 78
  • 101
  • 1
    This answer is no longer valid - asked a new question here: http://stackoverflow.com/questions/38703016/what-is-the-replacement-for-datemodifiernode-in-new-versions-of-django – Chozabu Aug 01 '16 at 15:46