I have a model, call it Foo
, which has an attribute created_at
which notes the time (UTC) when an instance was created.
I would like to annotate a query set over this model with the number of seconds since each item returned was created.
(to be more precise, I would like to "discount" items based on the time they have been open, with a configurable stale-out time, but I can do that computation if I can get the number of seconds since create)
I have tried some obvious things like
Foo.objects.annotate(time_since_create=now-F('created_at'))
and
Foo.objects.annotate(time_since_create=now.timestamp()-F('created_at'))
(where now is
utc.localize(datetime.utcnow())`)
but these get me AttributeError: 'float' object has no attribute 'tzinfo'
, which suggests that DB arithmetic on dates is a little more complex than I'm thinking it ought to be.
Obviously, I can do this arithmetic in python, ie,
[(id, now-created_at) for id, created_at in Foo.objects.values_list("id", "created_at")]
but it would be nicer if I could get this back in the queryset.