Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timedelta between two fields

I'm looking for objects where the timedelta between two fields is greater than a certain number of days.

Baiscally I have a date when a letter is sent, and a date when an approval is received. When no approval is received in let's say 30 days, then these objects should be included in the queryset.

I can do something like the below, where the delta is something static. However I don't need datetime.date.today() as a start but need to compare against the other object.

delta = datetime.date.today() - datetime.timedelta(30)
return qs.filter(letter_sent__isnull=False)\
    .filter(approval_from__isnull=True)\
    .filter(letter_sent__gte=delta)

Any pointer how to do this?

like image 469
SaeX Avatar asked Oct 11 '16 20:10

SaeX


1 Answers

Sounds like you want to annotate with an F object. Something like this:

from django.db.models import DurationField, ExpressionWrapper, F

delta = datetime.timedelta(days=30)
expression = F('approval_from') - F('letter_sent')
wrapped_expression = ExpressionWrapper(expression, DurationField())
qs = qs.annotate(delta=wrapped_expression)
qs = qs.filter(delta__gte=delta)
like image 194
wim Avatar answered Oct 27 '22 10:10

wim