看看这个模型(它是假设的):
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)
#...
我想要查询的是:汽车及其制造商的经理列表(给出一些在问题中不重要的条件)以及他们的城市。这可以通过以下代码完成:
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)
将列在字典中,由经理列出制造商的汽车,这就是我想要的。但是,此代码显然会在数据库中运行与汽车一样多的查询。
如何一次选择所有这些实例?
答案 0 :(得分:0)
可能是这样的事情(只是在我头顶编码):
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, [])