select_related在已经查询的字段上执行SQL查询吗?

时间:2018-11-21 10:49:45

标签: python django django-models orm django-orm

我们假设汽车有多个轮子,而一个轮子只有一种颜色。
第四行执行SQL查询吗?

cars = Car.objects.prefetch_related('wheel_set__color')
for car in cars:
    for wheel in car.wheel_set:
        print(wheel.color)

1 个答案:

答案 0 :(得分:0)

您的问题询问有关select_related()的问题,但是您的代码指定了prefetch_related(),所以我将同时解决这两个问题。

以下内容将一次访问数据库:

cars = Car.objects.select_related('wheel_set__color')
for car in cars:
    for wheel in car.wheel_set:
        print(wheel.color)

以下内容将三次访问数据库:

cars = Car.objects.prefetch_related('wheel_set__color')
for car in cars:
    for wheel in car.wheel_set:
        print(wheel.color)

但是,以下内容将两次访问数据库:

cars = Car.objects.select_related('wheel_set').prefetch_related('wheel_set__color')
for car in cars:
    for wheel in car.wheel_set:
        print(wheel.color)

https://docs.djangoproject.com/en/2.1/ref/models/querysets/#select-related