#7270 closed (fixed)
selected_related() can not follow reverse relations of OneToOne.
Reported by: | 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)
Change History (81)
comment:1 by , 17 years ago
Component: | Uncategorized → Database wrapper |
---|
by , 17 years ago
Attachment: | django_select_related_onetoone_r7534.patch added |
---|
comment:2 by , 17 years ago
thanks for the patch, but this also affects ForeignKeys and results in a extraordinary large invalid sql query:)
by , 16 years ago
Attachment: | django_select_related_onetoone_r7534.2.patch added |
---|
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 , 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 , 16 years ago
Attachment: | 121_reverse_r7601.patch added |
---|
comment:4 by , 16 years ago
Owner: | changed from | to
---|
by , 16 years ago
Attachment: | 121_reverse_r7831.patch added |
---|
Updated patch again r7831, friendlier towards FK(unique=True)
comment:6 by , 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 , 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 , 16 years ago
Triage Stage: | Unreviewed → Accepted |
---|
comment:9 by , 16 years ago
milestone: | 1.0 → post-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 , 16 years ago
Cc: | added |
---|---|
Keywords: | select_related onetoone reverse added |
comment:11 by , 16 years ago
The newest uploaded patch brings this to r8985, but in every other way is the same as the previous patch.
comment:13 by , 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 , 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 , 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 , 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 , 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 , 16 years ago
Cc: | added |
---|
comment:19 by , 16 years ago
Cc: | added |
---|
comment:20 by , 16 years ago
Cc: | added |
---|
comment:21 by , 16 years ago
Cc: | added |
---|
comment:22 by , 16 years ago
Cc: | added |
---|
comment:23 by , 16 years ago
Cc: | added |
---|
comment:24 by , 16 years ago
Cc: | added |
---|
comment:26 by , 16 years ago
Cc: | added |
---|---|
Owner: | changed from | to
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 , 16 years ago
Cc: | added |
---|
comment:28 by , 16 years ago
Cc: | added |
---|
comment:29 by , 16 years ago
milestone: | → 1.2 |
---|
comment:30 by , 16 years ago
Cc: | added |
---|
comment:31 by , 16 years ago
Cc: | 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.
comment:32 by , 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 , 16 years ago
Cc: | added |
---|
comment:34 by , 16 years ago
Cc: | added; removed |
---|
by , 16 years ago
Attachment: | django_select_related_onetoone_r10448.patch added |
---|
adaptation to the r10448
comment:35 by , 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 , 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 , 16 years ago
Attachment: | django_select_related_onetoone_r10454.patch added |
---|
Updated to always use LEFT OUTER JOINs, added back tests
comment:37 by , 16 years ago
Oops, just realized the tests somehow didn't make it into that patch. Patch updated.
comment:38 by , 16 years ago
Needs tests: | unset |
---|
comment:39 by , 16 years ago
Cc: | added |
---|
Recursive select_related() (with no fields specified) doesn't seem to work yet.
comment:40 by , 16 years ago
Patch needs improvement: | set |
---|
comment:41 by , 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 , 15 years ago
Owner: | changed from | to
---|---|
Status: | new → assigned |
comment:43 by , 15 years ago
Owner: | changed from | to
---|---|
Status: | assigned → new |
comment:44 by , 15 years ago
Cc: | added |
---|
comment:45 by , 15 years ago
Cc: | added |
---|
comment:46 by , 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 , 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 , 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 , 15 years ago
Cc: | added |
---|
by , 15 years ago
Attachment: | django_select_related_onetoone.patch added |
---|
patches against trunk, r11479
comment:50 by , 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 , 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 , 15 years ago
Cc: | added |
---|
follow-up: 54 comment:53 by , 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.
comment:54 by , 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 , 15 years ago
Cc: | added |
---|
comment:56 by , 15 years ago
Cc: | added |
---|
comment:57 by , 15 years ago
Cc: | added |
---|
comment:58 by , 15 years ago
Cc: | added |
---|
comment:59 by , 15 years ago
Cc: | added |
---|
comment:60 by , 15 years ago
Cc: | added |
---|
comment:61 by , 15 years ago
Cc: | added |
---|
comment:62 by , 15 years ago
Cc: | added |
---|
comment:63 by , 15 years ago
Keywords: | performance added |
---|
comment:64 by , 15 years ago
Cc: | added |
---|
by , 15 years ago
Attachment: | reverse_select_related.diff added |
---|
comment:65 by , 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 , 15 years ago
Resolution: | → fixed |
---|---|
Status: | new → closed |
comment:67 by , 15 years ago
Resolution: | fixed |
---|---|
Status: | closed → reopened |
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
by , 15 years ago
Attachment: | 12307-onetoone-null.patch added |
---|
comment:68 by , 15 years ago
Cc: | added |
---|
comment:69 by , 15 years ago
Resolution: | → fixed |
---|---|
Status: | reopened → closed |
The original issue here was fixed, please open a new bug for the new issue.
a dirty patch to fix this ticket.