Skip to content

Let SearchFilter subclasses dynamically set search fields #6279

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 19, 2019
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
7 changes: 7 additions & 0 deletions docs/api-guide/filtering.md
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,13 @@ For example:

By default, the search parameter is named `'search`', but this may be overridden with the `SEARCH_PARAM` setting.

To dynamically change search fields based on request content, it's possible to subclass the `SearchFilter` and override the `get_search_fields()` function. For example, the following subclass will only search on `title` if the query parameter `title_only` is in the request:

class CustomSearchFilter(self, view, request):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Did you mean:

class CustomSearchFilter(SearchFilter):
    def get_search_fields(self, view, request):
      ...

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, someone else noticed this in #6487.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for catching! Apologies for the mistake :(

if request.query_params.get('title_only'):
return ('title',)
return super(CustomSearchFilter, self).get_search_fields(view, request)

For more details, see the [Django documentation][search-django-admin].

---
Expand Down
10 changes: 9 additions & 1 deletion rest_framework/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,14 @@ class SearchFilter(BaseFilterBackend):
search_title = _('Search')
search_description = _('A search term.')

def get_search_fields(self, view, request):
"""
Search fields are obtained from the view, but the request is always
passed to this method. Sub-classes can override this method to
dynamically change the search fields based on request content.
"""
return getattr(view, 'search_fields', None)

def get_search_terms(self, request):
"""
Search terms are set by a ?search=... query parameter,
Expand Down Expand Up @@ -90,7 +98,7 @@ def must_call_distinct(self, queryset, search_fields):
return False

def filter_queryset(self, request, queryset, view):
search_fields = getattr(view, 'search_fields', None)
search_fields = self.get_search_fields(view, request)
search_terms = self.get_search_terms(request)

if not search_fields or not search_terms:
Expand Down
25 changes: 25 additions & 0 deletions tests/test_filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,31 @@ class SearchListView(generics.ListAPIView):

reload_module(filters)

def test_search_with_filter_subclass(self):
class CustomSearchFilter(filters.SearchFilter):
# Filter that dynamically changes search fields
def get_search_fields(self, view, request):
if request.query_params.get('title_only'):
return ('$title',)
return super(CustomSearchFilter, self).get_search_fields(view, request)

class SearchListView(generics.ListAPIView):
queryset = SearchFilterModel.objects.all()
serializer_class = SearchFilterSerializer
filter_backends = (CustomSearchFilter,)
search_fields = ('$title', '$text')

view = SearchListView.as_view()
request = factory.get('/', {'search': '^\w{3}$'})
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use raw strings to avoid Python warnings.

response = view(request)
assert len(response.data) == 10

request = factory.get('/', {'search': '^\w{3}$', 'title_only': 'true'})
response = view(request)
assert response.data == [
{'id': 3, 'title': 'zzz', 'text': 'cde'}
]


class AttributeModel(models.Model):
label = models.CharField(max_length=32)
Expand Down