I'm getting a weird error trying to select_related over multiple OneToOneField relationships, e.g. in the case where the target field is a grandchild subclass. I'd love someone to help me understand what's going on (or confirm that this is a bug in Django).
Illustration:
# models.py
from django.db import models
class A(models.Model):
pass
class B(A):
pass
class C(B):
pass
Simple enough, right? Now I open the Django shell with a clean database:
>>> C().save()
>>> A.objects.select_related('b__c')
[]
Wait, what? Why is that queryset empty? A quick sanity check:
>>> A.objects.select_related('b')[0].b.c
<C: C object>
So why doesn't the select_related call work? Well, watch this:
>>> A.objects.select_related('b__c').__iter__().next()
...
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/opt/webapps/asdf/lib/python2.6/site-packages/django/db/models/query.py", line 107, in _result_iter
self._fill_cache()
File "/opt/webapps/asdf/lib/python2.6/site-packages/django/db/models/query.py", line 772, in _fill_cache
self._result_cache.append(self._iter.next())
File "/opt/webapps/asdf/lib/python2.6/site-packages/django/db/models/query.py", line 273, in iterator
for row in compiler.results_iter():
File "/opt/webapps/asdf/lib/python2.6/site-packages/django/db/models/sql/compiler.py", line 680, in results_iter
for rows in self.execute_sql(MULTI):
File "/opt/webapps/asdf/lib/python2.6/site-packages/django/db/models/sql/compiler.py", line 725, in execute_sql
sql, params = self.as_sql()
File "/opt/webapps/asdf/lib/python2.6/site-packages/django/db/models/sql/compiler.py", line 58, in as_sql
self.pre_sql_setup()
File "/opt/webapps/asdf/lib/python2.6/site-packages/django/db/models/sql/compiler.py", line 29, in pre_sql_setup
self.fill_related_selections()
File "/opt/webapps/asdf/lib/python2.6/site-packages/django/db/models/sql/compiler.py", line 661, in fill_related_selections
used, next, restricted, new_nullable)
File "/opt/webapps/asdf/lib/python2.6/site-packages/django/db/models/sql/compiler.py", line 617, in fill_related_selections
chain = opts.get_base_chain(f.rel.to)
File "/opt/webapps/asdf/lib/python2.6/site-packages/django/db/models/options.py", line 452, in get_base_chain
% model._meta.module_name,)
TypeError: 'b' is not an ancestor of this model
>>>
So, is this a Django bug, or am I not understanding something?