使用Foreignkey和prefetch_related的getattr会导致多个SQL查询

时间:2018-02-14 20:24:18

标签: django django-models

我有三个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。

1 个答案:

答案 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'))