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_rela开发者_如何学编程ted('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?
Something like this, perhaps (just code off the top of my head):
cars = Car.objects.filter(...)
managers = {}
for manager in Manager.objects.filter(manufacturer__car__in=cars):
manufacturers = managers.setdefault(manager.manufacturer_id, [])
manufacturers.append(manager)
cars = list(cars)
for car in cars:
car.managers = managers.get(car.manufacturer_id, [])
精彩评论