﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
4789	select_related + depth gives wrong result	Gábor Farkas <gabor@…>	nobody	"i have a situation, where using select_related with depth=1 or depth=2 gives wrong results.
increasing depth to 3, or leaving out the depth parameter gives correct results.

the data to reproduce the problem:

models.py: (for this test-case, i assume that it is in the app called 'myapp')

{{{
from django.db.models import Model, ForeignKey, CharField

class Newsletter(Model):
    name = CharField(maxlength=128)

class Team(Model):
    name = CharField(maxlength=128)

class Group(Model):
    team = ForeignKey(Team)

class User(Model):
    group = ForeignKey(Group)

class Subscription(Model):
    user = ForeignKey(User)
    newsletter = ForeignKey(Newsletter)
}}}

use the following commands to trigger the problem:

{{{

from myapp import models

team = models.Team.objects.create(name='team')

group = models.Group.objects.create(team=team)

user = models.User.objects.create(group=group)

newsletter = models.Newsletter.objects.create(name='newsletter')

subscription = models.Subscription.objects.create(user=user, newsletter=newsletter)



q = models.Subscription.objects.filter(id=1)


print q[0].newsletter.name
print q.select_related(depth=0)[0].newsletter.name

print q.select_related(depth=1)[0].newsletter.name
print q.select_related(depth=2)[0].newsletter.name

print q.select_related(depth=3)[0].newsletter.name
}}}

it's output is
{{{
newsletter
newsletter
1
team
newsletter
}}}

the third and fourth line from the output (""1"" and ""team"") are clearly wrong, they should all give the same result.

notes:

1. tested on mac-osx with sqlite3 and postgresql8.2 with both psycopg1 and psycopg2 (from macports) (problem was also reproducible on ubuntu-linux). package versions for the mac-osx:
  * django: 5620
  * python: 2.4.4
  * sqlite3: 3.4.0
  * pysqlite: 2.3.3
  * psycopg: 1.1.21
  * psycopg2: 2.0.5
  * postgresql: 8.2.4

2. this is the shortest test-case i could come up with. if i make the ""foreignkey-chain"" shorter, the problem does not show up.

3. after examining the sql-queries that are generated for the 'wrong' queryset, it seems that the correct sql-query is generated, so probably the sql-query-result is incorrectly mapped to the objects.

4. this problem might be the same as the one discussed in #3623, but i am not sure, and also my test-case is smaller, so maybe easier to use."		closed	Database layer (models, ORM)	dev		duplicate	select_related, depth, qs-rf	gabor@… herbert.poul@…	Ready for checkin	1	0	0	0	0	0
