使用select_related获取两个模型的值

时间:2015-02-06 09:14:02

标签: python django django-select-related

假设我有以下内容:

class Model1(Model):

    field1 = ForeignKey(Model2)
    query_field = IntegerField()

class Model2(Model):
    field2 = ForeignKey(Model3)

class Model3(Model)
    field3 = SomeDesiredValue

现在,我想对Model1表格进行查询,并从field3中提取Model3。我的问题是关于select_related的表现。

如果我这样做

query = Model1.objects.filter(query_field=filter_paramter).select_related('field1')

我假设以下内容仍会访问数据库?

query[0].field1.field2.field3

我可以执行以下操作以加快速度吗?

query = Model1.objects.filter(query_field=filter_paramter).select_related('field1__field2')

2 个答案:

答案 0 :(得分:3)

是的,第一个查询会导致两个数据库命中,第二个查询将使用一个带有两个INNER JOINS的SQL查询来处理:

SELECT "app_model1"."id", "app_model1"."field1_id",
       "app_model1"."query_field", "app_model2"."id",
       "app_model2"."field2_id", "app_model3"."id",
       "app_model3"."field3"
FROM "app_model1"
INNER JOIN "app_model2" ON ( "app_model1"."field1_id" = "app_model2"."id" )
INNER JOIN "app_model3" ON ( "app_model2"."field2_id" = "app_model3"."id" )
WHERE "app_model1"."query_field" = 1 LIMIT 1

答案 1 :(得分:1)

class Model1(Model):

    field1 = ForeignKey(Model2, related_name="model2")
    query_field = IntegerField()

class Model2(Model):
    field2 = ForeignKey(Model3, related_name="model3")

class Model3(Model)
    field3 = SomeDesiredValue

并做这样的事情会更好。

mdls1 = Model1.objects.filter(query_field=filter_paramter).first()

related_model3s = mdls1.field1.model3.all()

这将从Model2获取所有field2(这意味着Model2与Model2相关)     如果您需要任何帮助,请询问:)