Take a look at this model (it's hypothetical):
class Manufacturer(models.Model):
#...
class Car(models.Model):
manufacturer = models.ForeignKey(Manufacturer)
#...
class City(models.Model):
#...
class Manager(models.Model):
manufacturer = models.ForeignKey(Manufacturer)
city = models.ForeignKey(City)
#...
What I want to query is: a list of cars and their manufacturer's managers (given a few conditions which are not important in the question), as well as their cities. This could somehow be done by the following code:
manager_car = defaultdict(list)
cars = Car.objects.select_related('manufacturer').filter(...)
for car in cars:
managers = car.manufacturer.manager_set.select_related('city').filter(...)
for manager in managers:
#if <optional condition>:
manager_car[manager].append(car)
Would list in a dictionary, the manufacturer's cars by manager, which is what I want. However, this code obviously runs as many queries as cars in the database.
How do I select all those instances at once?