Django - Filtering query by difference of two DateTimeFields
<p>I have a model with two DateTimeFields:</p>

<pre><code>starttime = models.DateTimeField(db_column='starttime', blank=False, null=False)
endtime = models.DateTimeField(db_column='endtime', blank=False, null=False)
</code></pre>

<p>In my view I would like to filter this by the difference between them. For example if the difference between start and end is more than 45 seconds.</p>

<p>I tried this as a guess:</p>

<pre><code>        .filter((models.F('endtime') - models.F('starttime')).seconds &gt; 45)\
</code></pre>

<p>But that didn't work. Is there a way to do this with the Django ORM?</p>

<p>You can use the F expression as shown below. </p>

<pre><code>from django.db.models import F
from django.utils import timezone


.filter(endtime__gt = models.F('starttime') + timezone.timedelta(0, 45))
</code></pre>

<p>It will return only the rows which endtime is greater than starttime + 45 seconds. </p>

python django