Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions rest_framework/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,8 @@ def must_call_distinct(self, queryset, search_fields):
continue
parts = search_field.split(LOOKUP_SEP)
for part in parts:
if part == "pk":
part = opts.pk.name
field = opts.get_field(part)
if hasattr(field, 'get_path_info'):
# This field is a relation, update opts to follow the relation
Expand Down
40 changes: 40 additions & 0 deletions tests/test_filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -451,6 +451,19 @@ def test_must_call_distinct(self):
["%stitle" % prefix, "%sattribute__label" % prefix]
)

def test_must_call_distinct_with_pk_alias(self):
filter_ = filters.SearchFilter()
prefixes = [''] + list(filter_.lookup_prefixes)
for prefix in prefixes:
assert not filter_.must_call_distinct(
SearchFilterModelFk._meta,
["%spk" % prefix]
)
assert not filter_.must_call_distinct(
SearchFilterModelFk._meta,
["%sattribute__pk" % prefix]
)

def test_must_call_distinct_restores_meta_for_each_field(self):
# In this test case the attribute of the fk model comes first in the
# list of search fields.
Expand Down Expand Up @@ -535,6 +548,33 @@ def test_must_call_distinct(self):
["%stitle" % prefix, "%sattributes__label" % prefix]
)

def test_must_call_distinct_with_pk_alias(self):
filter_ = filters.SearchFilter()
prefixes = [''] + list(filter_.lookup_prefixes)
for prefix in prefixes:
assert not filter_.must_call_distinct(
SearchFilterModelM2M._meta,
["%spk" % prefix]
)
assert filter_.must_call_distinct(
SearchFilterModelM2M._meta,
["%sattributes__pk" % prefix]
)

def test_search_on_pk(self):
class SearchListView(generics.ListAPIView):
queryset = SearchFilterModelM2M.objects.all()
serializer_class = SearchFilterM2MSerializer
filter_backends = (filters.SearchFilter,)
search_fields = ('=pk',)

pk = SearchFilterModelM2M.objects.get(title='zz').pk
view = SearchListView.as_view()
request = factory.get('/', {'search': str(pk)})
response = view(request)
assert response.status_code == 200
assert [item['title'] for item in response.data] == ['zz']


class Blog(models.Model):
name = models.CharField(max_length=20)
Expand Down
Loading