我有三个Django模型:
class One(models.Model):
title = models.CharField(max_length=5)
def __str__(self):
return self.title
class Two(models.Model):
title = models.CharField(max_length=5)
def __str__(self):
return self.title
class Three(models.Model):
one = models.ForeignKey(One)
two = models.ForeignKey(Two, null=True)
我有两个功能( EDITED ):
def get_one():
instances = Three.objects.all().select_related()
for instance in instances:
print(getattr(instance,'one'))
def get_two():
instances = Three.objects.all().select_related()
for instance in instances:
print(getattr(instance,'two'))
当我调用get_one()时,我得到one.title而没有额外的SQL查询但是使用get_two(),我有一个额外的SQL查询。如果我在两个中删除null = True,它就像一个。 我使用Django 1.9.5和MySQL。
答案 0 :(得分:0)
应该是select_related
而不是预取相关,因为在反向关系的情况下会使用prefetch_related
。
def get_one():
instances = Three.objects.all().select_related('one')
for instance in instances:
print(getattr(instance,'one'))
def get_two():
instances = Three.objects.all().select_related('two')
for instance in instances:
print(getattr(instance,'two'))