Opened 10 years ago

Closed 9 years ago

#23791 closed Bug (fixed)

Subqueries with non-"id" OneToOneField primary keys try to join against the wrong column name

Reported by: ris Owned by: nobody
Component: Database layer (models, ORM) Version: dev
Severity: Normal Keywords: orm primary_key OneToOneField subquery values
Cc: Triage Stage: Ready for checkin
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by ris)

Hi, your favourite ORM obscure-query bug reporter again here...

Using Django 1.7.1 & postgres, example models.py:

class ModelA ( models.Model ):
	x = models.TextField ()

class ModelB ( models.Model ):
	a = models.OneToOneField ( ModelA , primary_key = True )

issuing the query

>>> ModelB.objects.filter ( pk__in = ModelB.objects.filter ( a__x = "abc" ) )

results in

FieldError: Cannot resolve keyword u'id' into field. Choices are: a, a_id

A workaround exists:

>>> ModelB.objects.filter ( pk__in = ModelB.objects.filter ( a__x = "abc" ).values ( "pk" ) )

which behaves correctly.

Attachments (1)

23791-test.diff (526 bytes ) - added by Tim Graham 10 years ago.

Download all attachments as: .zip

Change History (6)

comment:1 by ris, 10 years ago

Description: modified (diff)

comment:2 by ris, 10 years ago

Having said the workaround behaves correctly, I realize adding .values (...) screws up the ordering of the subquery, which is important if using .distinct (...). Similar effects to #23622

Last edited 10 years ago by ris (previous) (diff)

comment:3 by Tim Graham, 10 years ago

Triage Stage: UnreviewedAccepted
Version: 1.7master

I can reproduce using the attached test. Doesn't appear to be a recent regression though (I tested back to 1.5).

by Tim Graham, 10 years ago

Attachment: 23791-test.diff added

comment:4 by Tim Graham, 9 years ago

Has patch: set
Triage Stage: AcceptedReady for checkin

PR from Anssi.

comment:5 by Tim Graham <timograham@…>, 9 years ago

Resolution: fixed
Status: newclosed

In 9ed8215:

Fixed #23791 -- Corrected object type check for pkin=qs

When the pk was a relation field, qs.filter(pkin=qs) didn't work.

In addition, fixed Restaurant.objects.filter(place=restaurant_instance),
where place is an OneToOneField and the primary key of Restaurant.

A big thank you to Josh for review and to Tim for review and cosmetic
edits.

Thanks to Beauhurst for commissioning the work on this ticket.

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