Description
Currently, the get_search_terms method of the SearchFilter class in Django Rest Framework does not provide access to the view instance. This limitation prevents developers from accessing view-specific configuration, such as custom deny-lists or other filtering requirements defined in the ViewSet.
For example, if a ViewSet defines a list of forbidden search terms (deny-list) that should be excluded from the search, there is currently no straightforward way to access this list within the get_search_terms method, since the view is not available as a parameter.
Proposed solution:
Add a view parameter to the get_search_terms method of SearchFilter, so that custom filtering logic can utilize attributes from the view.
Sample use case:
Suppose we want to provide different deny-lists of forbidden search terms in several ViewSets and filter them out in the get_search_terms method:
class MyViewSet(ModelViewSet):
queryset = MyModel.objects.all()
serializer_class = MyModelSerializer
filter_backends = [CustomSearchFilter]
search_fields = ['name', 'description']
search_deny_list = ['forbidden', 'secret'] # Custom deny-list
class MyViewSet2(ModelViewSet):
queryset = MyModel2.objects.all()
serializer_class = MyModel2Serializer
filter_backends = [CustomSearchFilter]
search_fields = ['name', 'location']
search_deny_list = ['disallowed'] # Custom deny-list
class CustomSearchFilter(SearchFilter):
def get_search_terms(self, request, view):
terms = super().get_search_terms(request, view)
deny_list = getattr(view, 'search_deny_list', [])
# Filter out forbidden terms
return [term for term in terms if term not in deny_list]
With the proposed change, developers could easily implement such custom logic by accessing view properties inside get_search_terms.