简体   繁体   中英

Cannot reduce "SELECT" queries with "select_related()" and "prefetch_related()" in one-to-one relationship in Django

I have Person and PersonDetail models in one-to-one relationship as shown below. *I use Django 3.2.16 :

class Person(models.Model):
    name = models.CharField(max_length=20)

    def __str__(self):
        return self.name

class PersonDetail(models.Model):
    person = models.OneToOneField(Person, on_delete=models.CASCADE) # Here
    age = models.IntegerField()
    gender = models.CharField(max_length=20)

    def __str__(self):
        return str(self.age) + " " + self.gender

Then, I have 5 objects for Person and PersonDetail models each:

在此处输入图像描述

在此处输入图像描述

Then, I iterate PersonDetail model from Person model as shown below:

for obj in Person.objects.all():
    print(obj.persondetail)

Or, I iterate PersonDetail model from Person model with select_related() as shown below:

for obj in Person.objects.select_related().all():
    print(obj.persondetail)

Or, I iterate PersonDetail model from Person model with prefetch_related() as shown below:

for obj in Person.objects.prefetch_related().all():
    print(obj.persondetail)

Then, these below are outputted on console:

32 Male
26 Female
18 Male
27 Female
57 Male

Then, 6 SELECT queries are run as shown below for all 3 cases of the code above. *I use PostgreSQL and these below are the query logs of PostgreSQL and you can see my answer explaining how to enable and disable the query logs on PostgreSQL:

在此处输入图像描述

So, I cannot reduce 5 SELECT queries with select_related() and prefetch_related() in one-to-one relationship in Django.

So, is it impossible to reduce SELECT queries with select_related() and prefetch_related() in one-to-one relationship in Django?

You will have to specify the name of the related field which in this case is persondetail , so:

for obj in Person.objects.select_related("persondetail").all():
    print(obj.persondetail)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM