1

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:

enter image description here

enter image description here

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:

enter image description here

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?

0

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.