Timedelta between two fields

2019-04-12 01:42发布

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?

2条回答
Summer. ? 凉城
2楼-- · 2019-04-12 02:42

You can also make it the other way around. Just keep F("num_days") outside of timedelta because timedelta doesn't know about F().

from datetime import timedelta
expression = F('approval_from') - timedelta(days=1) * F("num_days")
wrapped_expression = ExpressionWrapper(expression, DateTimeField())
qs = qs.annotate(letter_sent_annotation=wrapped_expression)
qs = qs.filter(letter_sent__gte=letter_sent_annotation)
查看更多
再贱就再见
3楼-- · 2019-04-12 02:47

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

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

delta = datetime.timedelta(days=30)
expression = F('approval_from') - F('letter_sent')
wrapped_expression = ExpressionWrapper(expression, DateTimeField())
qs = qs.objects.annotate(delta=wrapped_expression)
qs = qs.filter(delta__gte=delta)
查看更多
登录 后发表回答