Opened 9 years ago

Closed 9 years ago

#26523 closed Bug (duplicate)

Unable to select_related() an implicit one to one relationship in multi-table inheritance

Reported by: Paulo Owned by: nobody
Component: Database layer (models, ORM) Version: 1.8
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Given the following models:

class Fruit(models.Model):
    weight = models.PositiveIntegerField(default=100)


class Apple(Fruit):
    farmer = models.CharField(max_length=200, blank=True)


class Kiwi(models.Model):
    fruit = models.OneToOneField(Fruit)
    farmer = models.CharField(max_length=200, blank=True)

I would like to prefetch the fruit object related to an apple or kiwi.

So I ran the following:

In [2]: kiwi = Kiwi.objects.select_related('fruit').latest('id')
QUERY = u'SELECT "fruits_kiwi"."id", "fruits_kiwi"."fruit_id", "fruits_kiwi"."farmer", "fruits_fruit"."id", "fruits_fruit"."weight" FROM "fruits_kiwi" INNER JOIN "fruits_fruit" ON ( "fruits_kiwi"."fruit_id" = "fruits_fruit"."id" ) ORDER BY "fruits_kiwi"."id" DESC LIMIT 1' - PARAMS = () [0.84ms]

In [3]: kiwi.fruit
Out[3]: <Fruit: Fruit #00021>

As you can see, calling kiwi.fruit does not result in any extra queries.

Now I tried with Apple:

In [4]: apple = Apple.objects.select_related('fruit_ptr').latest('id')
QUERY = u'SELECT "fruits_fruit"."id", "fruits_fruit"."weight", "fruits_apple"."fruit_ptr_id", "fruits_apple"."farmer" FROM "fruits_apple" INNER JOIN "fruits_fruit" ON ( "fruits_apple"."fruit_ptr_id" = "fruits_fruit"."id" ) ORDER BY "fruits_apple"."fruit_ptr_id" DESC LIMIT 1' - PARAMS = () [0.31ms]

In [5]: apple.fruit_ptr
QUERY = u'SELECT "fruits_fruit"."id", "fruits_fruit"."weight" FROM "fruits_fruit" WHERE "fruits_fruit"."id" = %s' - PARAMS = (16,) [0.35ms]
Out[5]: <Fruit: Fruit #00016>

Calling apple.fruit_ptr results in a query to the database even though it's set to prefetch the related fruit.

I've traced the bug to https://github.com/django/django/blob/stable/1.8.x/django/db/models/query_utils.py#L186

Change History (1)

comment:1 by Tim Graham, 9 years ago

Resolution: duplicate
Status: newclosed
Summary: Unable to prefetch the implicit one to one relationshipUnable to select_related() an implicit one to one relationship in multi-table inheritance

I think it's a duplicate of #15250.

Note: See TracTickets for help on using tickets.
Back to Top