diff --git a/django/contrib/admin/utils.py b/django/contrib/admin/utils.py index 4d39693e5d..6e59c83548 100644 --- a/django/contrib/admin/utils.py +++ b/django/contrib/admin/utils.py @@ -32,6 +32,8 @@ def lookup_needs_distinct(opts, lookup_path): lookup_fields = lookup_fields[:-1] # Now go through the fields (following all relations) and look for an m2m for field_name in lookup_fields: + if field_name == 'pk': + field_name = opts.pk.name field = opts.get_field(field_name) if hasattr(field, 'get_path_info'): # This field is a relation, update opts to follow the relation diff --git a/tests/admin_changelist/tests.py b/tests/admin_changelist/tests.py index b6060ff9a3..03a7400d0c 100644 --- a/tests/admin_changelist/tests.py +++ b/tests/admin_changelist/tests.py @@ -414,6 +414,21 @@ class ChangeListTests(TestCase): # There's only one Concert instance self.assertEqual(cl.queryset.count(), 1) + def test_pk_in_search_fields(self): + band = Group.objects.create(name='The Hype') + Concert.objects.create(name='Woodstock', group=band) + + m = ConcertAdmin(Concert, custom_site) + m.search_fields = ['group__pk'] + + request = self.factory.get('/concert/', data={SEARCH_VAR: band.pk}) + cl = ChangeList(request, Concert, *get_changelist_args(m)) + self.assertEqual(cl.queryset.count(), 1) + + request = self.factory.get('/concert/', data={SEARCH_VAR: band.pk + 5}) + cl = ChangeList(request, Concert, *get_changelist_args(m)) + self.assertEqual(cl.queryset.count(), 0) + def test_no_distinct_for_m2m_in_list_filter_without_params(self): """ If a ManyToManyField is in list_filter but isn't in any lookup params,