Darkade
Darkade

Reputation: 947

Recursive query: comparing one field to another of the same class

I have a model similar to this one:

class Trip(models.Model):
    departure = models.DateTimeField()
    arrival = models.DateTimeField()

And I want to make a query that returns objects where the arrival is at least 2 hours later than the departure.

Trip.objects.filter(arrival__gt = "departure" + timedelta(hours=2))

Is this even possible? thanks

Upvotes: 2

Views: 178

Answers (1)

dani herrera
dani herrera

Reputation: 51655

You are looking for filters that reference fields ont the model

But what if you want to compare the value of a model field with another field on the same model?

See this sample:

>>> from datetime import timedelta
>>> Entry.objects.filter(mod_date__gt=F('pub_date') + timedelta(days=3))

For your case:

from django.db.models import F
Trip.objects.filter(arrival__gt = F('departure') + timedelta(hours=2))

Upvotes: 2

Related Questions