Opened 7 years ago

Closed 7 years ago

#7103 closed (worksforme)

select_related doesn't traverse nullable FK relations even when explictitly specified.

Reported by: Andy McCurdy <sedrik@…> Owned by: nobody
Component: Database layer (models, ORM) Version: master
Severity: Keywords: select_related
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: UI/UX:

Description

Just updated my svn to latest trunk to get qs-rf merger. Went to try to get select_related to work with some of my models with nullable foreign keys, and didn't have much luck. Made a simple test to demonstrate this. Documentation suggests that if explicitly specified, select_related should query nullable relations.

# models.py
from django.db import models

class Foo(models.Model):
    name = models.CharField(max_length=32)

class BarManager(models.Manager):
    def get_query_set(self):
        print "selecting related..."
        return super(BarManager, self).get_query_set().select_related('foo')
    
class Bar(models.Model):
    foo = models.ForeignKey(Foo, null=True)
    name = models.CharField(max_length=32)
    
    objects = BarManager()
    


# console
In [1]: f = Foo(name='test_foo')

In [2]: f.save()

In [3]: b = Bar(name='tst_bar', foo=f)

In [4]: b.save()

In [5]: from django.db import connection

In [6]: b1 = Bar.objects.get(pk=1)
selecting related...

In [7]: connection.queries[-1]
Out[7]: 
[{'sql': 'SELECT "test_bar"."id","test_bar"."foo_id","test_bar"."name" FROM "test_bar" WHERE ("test_bar"."id" = 1)',
  'time': '0.003'}]

Change History (3)

comment:1 Changed 7 years ago by Andy McCurdy <sedrik@…>

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset

comment:2 Changed 7 years ago by mtredinnick

Are you sure you're running the right code? I cannot repeat this with any database backend or any combination of select_related() in the manager or otherwise (using your models and your console output).

Please check

>>> import django
>>> django.get_version()

to make sure you're running the latest trunk code.

If you are running the latest of everything, please provide details on python version, database backend and version, operating system, prevailing wind direction ... anything that might be a differentiating factor here. I cannot, for the life of me, see why this wouldn't be working from looking at the code (plus, it's something we test).

comment:3 Changed 7 years ago by Andy McCurdy <sedrik@…>

  • Resolution set to worksforme
  • Status changed from new to closed

Ya, I'm a bonehead. I had a rogue version of Python installed on OSX, and installing the latest Django wrote to the wrong python directory. My bad, Sorry.

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