Amen
Amen

Reputation: 47

Chaining multiple filter() in Django returning nothing

I was trying to filter two conditions but it's not returning anything That's the function that has the condition i'm using

def airport_view(request, code):
    airport = Airport.objects.get(code=code)
    flights = Flight.objects.filter(origin=airport).filter(destination=airport)
    context = {
        'airport':airport,
        'flights':flights
    }
    return render(request, "flights/airport.html", context)

The airport works normally but the multiple filter chain doesn't work, even that i got three flights which has one of both conditions That's the related models if it helps you

class Airport(models.Model):
    code = models.CharField(max_length=64)
    name = models.CharField(max_length=64)

class Flight(models.Model):
    origin = models.ForeignKey('Airport', on_delete=models.CASCADE, related_name="From")
    destination = models.ForeignKey('Airport', on_delete=models.CASCADE,related_name="To")
    passengers = models.ManyToManyField('Person', blank=True)

Upvotes: 1

Views: 158

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476659

For a disjunction of conditions, you can work with Q objects:

from django.db.models import Q

flights = Flight.objects.filter(Q(origin=airport) | Q(destination=airport))

this will retrieve Flights that have as origin, or as destination the given airport.

If you chain the filters together, you define a conjunction, so in this case you were looking for Flights that had as origin and as destination the airport.


Note: It is often better to use get_object_or_404(…) [Django-doc], then to use .get(…) [Django-doc] directly. In case the object does not exists, for example because the user altered the URL themselves, the get_object_or_404(…) will result in returning a HTTP 404 Not Found response, whereas using .get(…) will result in a HTTP 500 Server Error.

Upvotes: 2

Related Questions