Opened 17 years ago

Closed 15 years ago

Last modified 13 years ago

#7270 closed (fixed)

selected_related() can not follow reverse relations of OneToOne.

Reported by: towjzhou@… Owned by: Malcolm Tredinnick
Component: Database layer (models, ORM) Version: dev
Severity: Keywords: select_related onetoone reverse performance
Cc: oyvind.altvik@…, brent.hagany@…, elsdoerfer@…, gregoire@…, andrewbadr.etc@…, anossov@…, kimavr@…, dbronner@…, George Vilches, Boobsd@…, vbmendes@…, bendavis78@…, aiev.an.tks@…, nikitka@…, glennfmaynard@…, ionel.mc@…, Jim Garrison, dexterbt1@…, jdunck@…, kmike84@…, vinilios@…, oldium.pro@…, nicola.murino@…, mike@…, daemianmack@…, hgeerts@…, powderflask@…, David Larlet, s.angel@… Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Here are my models:

# The base model
class User(models.Model):
    username = models.CharField()
    password = models.CharField()

# The model holds extra info to User
class UserProfile(models.Model):
    user  = models.OneToOneField(User)
    address = models.CharField()

# Then query the user with extra info:
    users = User.objects.select_related('userprofile')

Above code can't work, because select_related only accepts ForeignKey fields.

Attachments (11)

django_select_related_onetoone_r7534.patch (2.2 KB ) - added by towjzhou@… 17 years ago.
a dirty patch to fix this ticket.
django_select_related_onetoone_r7534.2.patch (2.4 KB ) - added by towjzhou@… 16 years ago.
A updated patch to fix this ticket. This patch only work in select(fields...) mode, not effect on select()/select(depth=?) mode.
121_reverse_r7601.patch (9.6 KB ) - added by George Vilches 16 years ago.
121_reverse_r7831.patch (21.1 KB ) - added by George Vilches 16 years ago.
Updated patch again r7831, friendlier towards FK(unique=True)
121_reverse_r8985.patch (21.5 KB ) - added by George Vilches 16 years ago.
121 reverse patch updated to r8985.
121_reverse_r10396.patch (21.2 KB ) - added by Ben Davis 16 years ago.
121_reverse_patch updated to 10396
django_select_related_onetoone_r10448.patch (6.9 KB ) - added by aiev 16 years ago.
adaptation to the r10448
django_select_related_onetoone_r10454.patch (22.4 KB ) - added by Ben Davis 16 years ago.
Updated to always use LEFT OUTER JOINs, added back tests
django_select_related_onetoone.patch (9.1 KB ) - added by Ben Davis 15 years ago.
patches against trunk, r11479
reverse_select_related.diff (11.5 KB ) - added by Alex Gaynor 15 years ago.
12307-onetoone-null.patch (639 bytes ) - added by s.angel@… 15 years ago.
http://code.djangoproject.com/ticket/7270#comment:67

Download all attachments as: .zip

Change History (81)

comment:1 by anonymous, 17 years ago

Component: UncategorizedDatabase wrapper

by towjzhou@…, 17 years ago

a dirty patch to fix this ticket.

comment:2 by marc.boeker@…, 17 years ago

thanks for the patch, but this also affects ForeignKeys and results in a extraordinary large invalid sql query:)

by towjzhou@…, 16 years ago

A updated patch to fix this ticket. This patch only work in select(fields...) mode, not effect on select()/select(depth=?) mode.

comment:3 by George Vilches, 16 years ago

The newly attached patch is another approach to doing this, and shares some points with the original ticket creator. However, this patch also covers reverse caching, safely handles following all types of ForeignKeys attached to OneToOneFields, and includes unit tests and documentation.

by George Vilches, 16 years ago

Attachment: 121_reverse_r7601.patch added

comment:4 by George Vilches, 16 years ago

Owner: changed from nobody to George Vilches

by George Vilches, 16 years ago

Attachment: 121_reverse_r7831.patch added

Updated patch again r7831, friendlier towards FK(unique=True)

comment:5 by miracle2k, 16 years ago

Should be in a 1.0 milestone?

comment:6 by George Vilches, 16 years ago

milestone: 1.0

Some conversations I've had with core devs make me think so, so I'm updating the milestone appropriately.

comment:7 by Malcolm Tredinnick, 16 years ago

This is kind of "1.0 maybe if we get time", which really means before the beta release next week. It'd be nice to have in and it's probably very close to right, but if we don't get it in, the world won't end either.

comment:8 by Malcolm Tredinnick, 16 years ago

Triage Stage: UnreviewedAccepted

comment:9 by Malcolm Tredinnick, 16 years ago

milestone: 1.0post-1.0

Moving this to post-1.0, in line with my above comment. I know gav has done a lot of work on this (thanks for that, George!) and it would be nice to get it in, but I've just reread the patch and, although it looks correct, it does hit a lot of code that is used frequently and can hide subtle bugs. In the interests of stability (and feature freeze), it can wait,

comment:10 by oyvind, 16 years ago

Cc: oyvind.altvik@… added
Keywords: select_related onetoone reverse added

by George Vilches, 16 years ago

Attachment: 121_reverse_r8985.patch added

121 reverse patch updated to r8985.

comment:11 by George Vilches, 16 years ago

The newest uploaded patch brings this to r8985, but in every other way is the same as the previous patch.

comment:12 by oyvind, 16 years ago

Has patch: set

Seems sound to me, and the tests pass.

comment:13 by Robin, 16 years ago

How would I go about making the patch use LEFT JOIN (or LEFT OUTER JOIN) instead of INNER JOIN?

comment:14 by George Vilches, 16 years ago

This patch automatically makes the LEFT JOIN for any FK relationships where null=True. You should not have to do anything beyond this.

comment:15 by Robin, 16 years ago

Since this is a one-to-one relationship, the foreign key is also the primary key, so null is never true, hence LEFT JOIN will never occur unless forced somehow.

comment:16 by Malcolm Tredinnick, 16 years ago

There's a bug in the patch, robin. Reverse one-to-one's always have to use an outer join, since there's no guarantee that the related object exists (they are all nullable relationships when followed in reverse). I'll fix this when I commit the change; I noticed it before and have a note about it. That will happen, soon.

comment:17 by Malcolm Tredinnick, 16 years ago

(Oh, I should point out that it doesn't have to be an outer join if we're already filtering against that relation and didn't need an outer join the first time.)

comment:18 by Brent Hagany, 16 years ago

Cc: brent.hagany@… added

comment:19 by miracle2k, 16 years ago

Cc: elsdoerfer@… added

comment:20 by gregoire, 16 years ago

Cc: gregoire@… added

comment:21 by Andrew Badr, 16 years ago

Cc: andrewbadr.etc@… added

comment:22 by Pavel Anossov, 16 years ago

Cc: anossov@… added

comment:23 by kiriyama, 16 years ago

Cc: kimavr@… added

comment:24 by dbronner, 16 years ago

Cc: dbronner@… added

comment:25 by (none), 16 years ago

milestone: post-1.0

Milestone post-1.0 deleted

comment:26 by Malcolm Tredinnick, 16 years ago

Cc: George Vilches added
Owner: changed from George Vilches to Malcolm Tredinnick

Assigning to me so that it appears on my list of tickets to deal with. Will reassign back to gav if any insurmountable problem emerges, but I think this is pretty close to what we can use.

comment:27 by Boo, 16 years ago

Cc: Boobsd@… added

comment:28 by vbmendes, 16 years ago

Cc: vbmendes@… added

comment:29 by Malcolm Tredinnick, 16 years ago

milestone: 1.2

comment:30 by anonymous, 16 years ago

Cc: bendavis78@… added

comment:31 by aiev, 16 years ago

Cc: aiev.an.tks@… added
Needs tests: set
Patch needs improvement: set

I use the svn version and when I apply the patch with command "patch -p0 -i ~/121_reverse_r8985.patch" ocurrence some errors because the merge dont work correctly.

But when I aplly the patch manually and debug some lines it work! :D

Why it has not yet been implemented in current version? :( Just curiosity

Thanks.

by Ben Davis, 16 years ago

Attachment: 121_reverse_r10396.patch added

121_reverse_patch updated to 10396

comment:32 by Ben Davis, 16 years ago

I've attached a version of the patch against r10396.

Also, I modified the self.join() call to set promote=True so that LEFT OUTER joins are always used -- although I'm not sure if that was all I needed to do, as I'm seeing a problem with the returned queryset when some of the joined values are null.

For example, let's say we have some User records that don't have associated UserProfile records. When we do:

>>> print User.objects.select_related('userprofile').query.as_sql()[0]
'SELECT `auth_user`.`id`, `myapp_userprofile`.`id`, FROM `auth_user` LEFT OUTER JOIN `myapp_userprofile` ON (`auth_user`.`id` = `myapps_userprofile`.`user_id`)'

... we get the correct SQL, and running this in dbshell returns the correct results, with the columns from UserProfile set to NULL.

However, when we try to output the queryset object, we get an empty list:

>>> q = User.objects.select_related('user_profile')
>>> q
[]
>>> 

Any ideas on why this is occurring?

Also, I've noticed some other problems that come up when we .values() or .only() on the query set, so I think this patch needs a little more refining before we can get it to work.

comment:33 by anonymous, 16 years ago

Cc: niktika@… added

comment:34 by anonymous, 16 years ago

Cc: nikitka@… added; niktika@… removed

by aiev, 16 years ago

adaptation to the r10448

comment:35 by aiev, 16 years ago

A updated patch, no bug like:

>>> q = User.objects.select_related('user_profile')
>>> q
[]
>>> 

But the problem persists when we .only() on the query set.

The .values() works fine, right?

comment:36 by Ben Davis, 16 years ago

Patch needs improvement: unset

aiev, thanks. That seemed to fix the problem I was having :-) Although you left out the change I made in the last patch that forces the join to always be LEFT OUTER, as mtredinnick explained above. I've attached an updated patch.

by Ben Davis, 16 years ago

Updated to always use LEFT OUTER JOINs, added back tests

comment:37 by Ben Davis, 16 years ago

Oops, just realized the tests somehow didn't make it into that patch. Patch updated.

comment:38 by Ben Davis, 16 years ago

Needs tests: unset

comment:39 by Glenn Maynard, 16 years ago

Cc: glennfmaynard@… added

Recursive select_related() (with no fields specified) doesn't seem to work yet.

comment:40 by Ben Davis, 16 years ago

Patch needs improvement: set

comment:41 by Ben Davis, 15 years ago

Needs tests: set
Patch needs improvement: unset

Ok, I've updated the patch and fixed some code that was mysteriously duplicated, as well as fixed the tests that were written for the select_related change (they just needed init files).

I also believe I have the .values() query working with reverse one-to-one relationships, though I'd really like mtredinnick to take a look at the change since he's the one that wrote the original code for this. The change was fairly simple. In the setup_joins function in db/models/sql/query.py:

                     raise FieldError("Cannot resolve keyword %r into field. "
                             "Choices are: %s" % (name, ", ".join(names)))

-            if not allow_many and (m2m or not direct):
+            if not allow_many and m2m:
                 for alias in joins:
                     self.unref_alias(alias)
                 raise MultiJoin(pos + 1)

Looking at the original code, I'm not sure why "indirect" fields were not allowed if they weren't many-to-many relationships. This is basically what was keeping the reverse one-to-one lookups from working. I'm not 100% sure of the consequences of this change, but all model tests seemed to pass with this change.

@mtredinnick: thoughts?

We still need a test for this particular change, so I'm leaving "Needs tests" checked for now.

comment:42 by Ionel Cristian Maries, 15 years ago

Owner: changed from Malcolm Tredinnick to Ionel Cristian Maries
Status: newassigned

comment:43 by Ionel Cristian Maries, 15 years ago

Owner: changed from Ionel Cristian Maries to Malcolm Tredinnick
Status: assignednew

comment:44 by Ionel Cristian Maries, 15 years ago

Cc: ionel.mc@… added

comment:45 by Jim Garrison, 15 years ago

Cc: Jim Garrison added

comment:46 by Jim Garrison, 15 years ago

Why not make this (following reverse relationships as well as forward ones) the default behavior if select_related() is given no arguments?

comment:47 by Ben Davis, 15 years ago

I'm honestly not sure why the attached patch hasn't made it in -- I've been using it in my production environments and haven't had any problems. I was waiting on some feedback from mtredinnick, as to what the "if not allow_many and (m2m or not direct)" was for, but I'm not sure if he's following this ...

comment:48 by Chris Beaven, 15 years ago

It's not ready for checkin, because it's missing the test (you marked it as such). After the test is added, feel free to bring it up in the dev google group.

comment:49 by anonymous, 15 years ago

Cc: dexterbt1@… added

by Ben Davis, 15 years ago

patches against trunk, r11479

comment:50 by Ben Davis, 15 years ago

Needs tests: unset

Ok, I've update the patch for the r11479, and have included a basic test (it's my first time for this, so please advise if it needs to be better).

comment:51 by dchristian, 15 years ago

Patch fails when the relationship is held on a base class.

class A(models.Model):

pass

class B(A):

pass

class C(models.Model):

a_ref = models.OneToOneField('A', related_name='c_list')

B.objects.select_related('c_list')

fails. Reproducing from memory as I am not using this patch now. In any case it's pretty clear that the patch ignores base classes.

comment:52 by anonymous, 15 years ago

Cc: jdunck@… added

comment:53 by Ben Davis, 15 years ago

@dchristian: I'm a bit confused by your use case there, as I don't see how that particular setup would be used in a real-world situation. That is, I'm having trouble seeing a situation where I would have a one-to-one referencing a base model. If you could provide a more real-world example that would help.

in reply to:  53 comment:54 by dchristian, 15 years ago

We have a generic Content type, and a Article type that is a more specific type of content. Content is linked to by other sub-objects, one of which is a OneToOne but is kept in a different app to keep things separated nicely.

But in any case, the point is that this patch, if applied, will result in tracebacks when used in that situation, so I wouldn't recommend approving it until the situation is at least handled in some way that doesn't crash.

comment:55 by anonymous, 15 years ago

Cc: kmike84@… added

comment:56 by anonymous, 15 years ago

Cc: vinilios@… added

comment:57 by Oldřich Jedlička, 15 years ago

Cc: oldium.pro@… added

comment:58 by drakkan <nicola.murino@…>, 15 years ago

Cc: nicola.murino@… added

comment:59 by anonymous, 15 years ago

Cc: mike@… added

comment:60 by daemianmack, 15 years ago

Cc: daemianmack@… added

comment:61 by Harm Geerts <hgeerts@…>, 15 years ago

Cc: hgeerts@… added

comment:62 by powderflask, 15 years ago

Cc: powderflask@… added

comment:63 by anonymous, 15 years ago

Keywords: performance added

comment:64 by David Larlet, 15 years ago

Cc: David Larlet added

by Alex Gaynor, 15 years ago

Attachment: reverse_select_related.diff added

comment:65 by Alex Gaynor, 15 years ago

This new version passes all tests (both the ones it introduces and the existing ones), I didn't implement the reverse-fkey support because it seemed a bit hacky to me. Any other test cases would be great.

comment:66 by Russell Keith-Magee, 15 years ago

Resolution: fixed
Status: newclosed

(In [12307]) Fixed #7270 -- Added the ability to follow reverse OneToOneFields in select_related(). Thanks to George Vilches, Ben Davis, and Alex Gaynor for their work on various stages of this patch.

comment:67 by s.angel@…, 15 years ago

Resolution: fixed
Status: closedreopened

The commit [12307] has a bug. If i use select_related with a OneToOneField which can be null, if for the FIRST object, this relation is null, then it's give me an error

A path is joined

comment:68 by anonymous, 15 years ago

Cc: s.angel@… added

comment:69 by Alex Gaynor, 15 years ago

Resolution: fixed
Status: reopenedclosed

The original issue here was fixed, please open a new bug for the new issue.

comment:70 by Jacob, 13 years ago

milestone: 1.2

Milestone 1.2 deleted

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