How to filter an object witch has one of the two foreign key relation in Django one to many relationship

Viewed 53

I have city and routes models

class City(LocationAbstractModel):
    name        = models.CharField(max_length=255)

    def __str__(self):
        return self.name

class Route(BusAbstractModel):
    leaving_from = models.ForeignKey(location_models.City, on_delete=models.CASCADE, related_name='leaving_from')
    destination = models.ForeignKey(location_models.City, on_delete=models.CASCADE, related_name='destination')
    distance = models.IntegerField(null=True, blank=True)
    prices = models.ManyToManyField(carrier_models.Carrier, through="RoutePrice")
    crossing_cities = models.ManyToManyField(location_models.City, blank=True)

    def price(self, carrier_id):
        return self.routeprice_set.filter(carrier_id=carrier_id).order_by('created_at').first().price

    def __str__(self):
        return self.leaving_from.name + " -> " + self.destination.name

How can I query only cities which has one of the relation in routes model. I want to filter cities which has either leaving_from or destination relation ship.

I have tried

models.City.objects.filter(Q(route__leaving_from__isnull=False) |Q(route__destination__isnull=False)).distinct()

but it is only returning cities which has relation on both leaving_from and destination.

How can I Filter Cities which has one of the relationships

0 Answers
Related