diff --git a/django/db/models/fields/related_lookups.py b/django/db/models/fields/related_lookups.py index 8063ea801a..62bc92b6ff 100644 --- a/django/db/models/fields/related_lookups.py +++ b/django/db/models/fields/related_lookups.py @@ -83,7 +83,8 @@ class RelatedIn(In): else: if getattr(self.rhs, '_forced_pk', False): self.rhs.clear_select_clause() - if getattr(self.lhs.output_field, 'primary_key', False): + if (getattr(self.lhs.output_field, 'primary_key', False) and + self.lhs.output_field.model == self.rhs.model): # A case like Restaurant.objects.filter(place__in=restaurant_qs), # where place is a OneToOneField and the primary key of # Restaurant. diff --git a/docs/releases/1.11.1.txt b/docs/releases/1.11.1.txt index a10f3f47ef..066127d5e4 100644 --- a/docs/releases/1.11.1.txt +++ b/docs/releases/1.11.1.txt @@ -18,3 +18,6 @@ Bugfixes * Fixed a crash when using a two-tuple in ``EmailMessage``’s ``attachments`` argument (:ticket:`28042`). + +* Fixed ``QuerySet.filter()`` crash when it references the name of a + ``OneToOneField`` primary key (:ticket:`28047`). diff --git a/tests/one_to_one/tests.py b/tests/one_to_one/tests.py index b0843084c2..67eed38a93 100644 --- a/tests/one_to_one/tests.py +++ b/tests/one_to_one/tests.py @@ -479,6 +479,10 @@ class OneToOneTests(TestCase): pk__in=Restaurant.objects.filter(place__id=r.place.pk) ) self.assertSequenceEqual(q2, [r]) + q3 = Restaurant.objects.filter(place__in=Place.objects.all()) + self.assertSequenceEqual(q3, [r]) + q4 = Restaurant.objects.filter(place__in=Place.objects.filter(id=r.pk)) + self.assertSequenceEqual(q4, [r]) def test_rel_pk_exact(self): r = Restaurant.objects.first()