这是一个简单的问题:
是否有意义,或者是否可以将select_related
链接到这样的查询上?:
queryset = a.objects.filter(...).select_related("b").select_related("c")
A有一个ForeignKey到B,B有一个ForeignKey到C.我的模型看起来像这样:
class A(models.Model):
b = models.ForeignKey(B)
class B(models.Model):
c = models.ForeignKey(C)
答案 0 :(得分:6)
试试这个:
queryset = a.objects.filter(...).select_related("b__c")
from django.db import models
class City(models.Model):
# ...
pass
class Person(models.Model):
# ...
hometown = models.ForeignKey(City)
class Book(models.Model):
# ...
author = models.ForeignKey(Person)
和查询:
b = Book.objects.select_related('author__hometown').get(id=4)
p = b.author # Doesn't hit the database.
c = p.hometown # Doesn't hit the database.