1

看看这个模型(它是假设的):

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)

会在字典中按经理列出制造商的汽车,这就是我想要的。但是,这段代码显然运行了与数据库中的汽车一样多的查询。

如何一次选择所有这些实例?

4

1 回答 1

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, [])
于 2010-09-22T05:29:56.103 回答