Usage of select_related() on a OneToOneField with parent_link=True doesn't work

171 views
Skip to first unread message

Gilad

unread,
Nov 14, 2015, 8:03:56 AM11/14/15
to Django users
Hi,
Using Django 1.8.3, I have 2 models, both unmanaged (remote DB managed by another system), with something similar to that:

class Parent(Model):
... some fields...

class Child(Model):
id = OneToOneField(primary_key=True, parent_link=True)
... some other fields ...

Notes:
  1. Parent is not abstract.
  2. Each of the models have their own real tables.
  3. Not using model inheritance because I want the parent_link field to be called "id" (as the db column), and Django doesn't allow hiding fields (with the same name).
Given all that, using select_related('id') in a Child QuerySet doesn't work (no exception but the Parent fields aren't fetched in the same DB query).
In order to workaround the issue, I removed the parent_link attribute (note that as the tables are unmanaged, this attribute, and others, exist merely as documentation, so I can remove it).
Without the parent_link attribute, the Child fields are indeed fetched in the same DB query, as expected from select_related().

Is it a bug in Django or something I'm missing?

Simon Charette

unread,
Nov 14, 2015, 10:36:24 AM11/14/15
to Django users
Hi Gilad,

The `parent_link` option can only be used if the model the o2o field is pointing to is a direct base of the model it's attached to. From what I understand `select_related` simply ignores `parent_link` fields since it assumes it's pointing to a MTI parent table which are JOINed by default (unless values() and friends are involved).

Django should warn you about this. Please file a new bug ticket so we don't loose track of this issue.

Thanks!
Simon
Reply all
Reply to author
Forward
0 new messages