Opened 12 years ago

Closed 12 years ago

#19870 closed Bug (fixed)

select_related has issues with models linked by a FK which inherit from a common model

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

Description

Considering the following models:

class Fowl(models.Model):
    name = models.CharField(max_length=10)

class Hen(Fowl):
    pass

class Chick(Fowl):
    mother = models.ForeignKey(Hen)

Chick.objects.select_related()[0].mother would return a Hen model instance, but the value of its fields inherited from Fowl would be set to the value of the fields of the queried Chick.

The issue lies somewhere in the query generation as I tried the generated query in an SQL shell and it indeed pulls the Chick fields inherited from Fowl twice. This has probably something to do with table aliases.

Unlike most other select_related issues that simply fail to provide an optimization, this issue returns a faulty output which is pretty serious. Also worth mentioning, the admin calls select_related on every field present in list_display which leads to ChangeList displaying completely incorrect data .

Attachments (1)

select_related_regress.patch (1.8 KB ) - added by loic84 12 years ago.

Download all attachments as: .zip

Change History (4)

by loic84, 12 years ago

comment:1 by Anssi Kääriäinen, 12 years ago

This seems to be master-only regression. 1.4 and 1.5 do not have this according to the test. I know who git blame will point out for this issue...

comment:2 by Anssi Kääriäinen, 12 years ago

Triage Stage: UnreviewedAccepted

comment:3 by Anssi Kääriäinen <akaariai@…>, 12 years ago

Resolution: fixed
Status: newclosed

In 3c6318e831658b88ba7c3e04f315329071b25e34:

Fixed #19870 -- Regression in select_related in inheritance cases

There was a regression in case two models inherited the same parent,
and one contained a foreign key to other. When select_related travelled
the foreign key the other model reused the parent join made by the
first model. This was likely caused by Query.join_parent_model()
addition in commit 68985db48212c701a3d975636123a5d79bdc006f.

Thanks to Trac alias loic84 for report & tests.

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