Code

Opened 6 years ago

Closed 6 years ago

#6571 closed (duplicate)

select_related(depth=1) selects one level more than it should

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

Description

Hi,

select_related(depth=1) does select one level more than it
should.

The problem is that django.db.models.query.fill_table_cache has cur_depth=0
by default and checks if max_depth and max_depth > cur_depth. That means that
max_depth has to catch up to cur_depth one round, before it works as expected.

Changing cur_depth to 1 or checking max_depth >= cur_depth would solve
the problem but i don't know whether it introduces any other problems.

Regards

class Foo(models.Model):

bar = models.ForeignKey(Bar)

class Bar(models.Model):

foo_bar = models.ForeignKey(FooBar)

class Foobar(models.Model):

pass


Foo.objetcs.select_related(depth=1)
from django.db import connection
print connection.queries[-1]sql?

.... FROM foo, bar, foobar ....


Foo.objetcs.select_related(depth=1)
from django.db import connection
print connection.queries[-1]sql?

.... FROM foo, bar ....

Attachments (1)

fill_table_cache.patch (450 bytes) - added by moep 6 years ago.

Download all attachments as: .zip

Change History (4)

comment:1 Changed 6 years ago by moep

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

Forgot that we have a wiki here

file foo.py

class Foo(models.Model):
	bar = models.ForeignKey(Bar)

class Bar(models.Model):
	foo_bar = models.ForeignKey(FooBar)

class Foobar(models.Model):
	pass

with cur_depth=0
$ from foo import Foo
$ Foo.objetcs.select_related(depth=1)
$ from django.db import connection
$ print connection.queries[-1]['sql']
>>> .... FROM foo, bar, foobar ....

with cur_depth=1 or max_depth >= cur_depth
$ from foo import Foo
$ Foo.objetcs.select_related(depth=1)
$ from django.db import connection
$ print connection.queries[-1]['sql']
>>> .... FROM foo, bar ....

Changed 6 years ago by moep

comment:2 Changed 6 years ago by moep

  • Has patch set

comment:3 Changed 6 years ago by mtredinnick

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

Dupe of #6018, amongst many others.

Add Comment

Modify Ticket

Change Properties
<Author field>
Action
as closed
as The resolution will be set. Next status will be 'closed'
The resolution will be deleted. Next status will be 'new'
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.