Skip to content
Advertisement

Django – complicated ORM Query (related_set)

I have model Car, Listing and Website.

class Listing..
    car = ForeignKey...
    website = ForeignKey...
    active = BooleanField...

I want to filter all car objects that have listing object on the given website but the listing needs to be active.

To get all car objects that have listing object on the given website:

website = ...
Car.objects.filter(listings__website__in=website)

But how do I filter out inactive listings?

I want something like:

website = ...
Car.objects.filter(listings[only_active]__website__in=website)

Advertisement

Answer

You would do an extra condition on your filter:

Car.objects.filter(listings__website__in=website, listings__active=True)
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement