mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-08-04 20:40:14 +03:00
Merge 30ee7a54b7
into fd72a814f8
This commit is contained in:
commit
57ec4d42eb
|
@ -77,6 +77,7 @@ class DjangoFilterBackend(BaseFilterBackend):
|
|||
class SearchFilter(BaseFilterBackend):
|
||||
# The URL query parameter used for the search.
|
||||
search_param = api_settings.SEARCH_PARAM
|
||||
search_fields_property = "search_fields"
|
||||
template = 'rest_framework/filters/search.html'
|
||||
lookup_prefixes = {
|
||||
'^': 'istartswith',
|
||||
|
@ -124,7 +125,7 @@ class SearchFilter(BaseFilterBackend):
|
|||
return False
|
||||
|
||||
def filter_queryset(self, request, queryset, view):
|
||||
search_fields = getattr(view, 'search_fields', None)
|
||||
search_fields = getattr(view, self.search_fields_property, None)
|
||||
search_terms = self.get_search_terms(request)
|
||||
|
||||
if not search_fields or not search_terms:
|
||||
|
@ -152,7 +153,7 @@ class SearchFilter(BaseFilterBackend):
|
|||
return queryset
|
||||
|
||||
def to_html(self, request, queryset, view):
|
||||
if not getattr(view, 'search_fields', None):
|
||||
if not getattr(view, self.search_fields_property, None):
|
||||
return ''
|
||||
|
||||
term = self.get_search_terms(request)
|
||||
|
|
|
@ -526,6 +526,28 @@ class SearchFilterTests(TestCase):
|
|||
|
||||
reload_module(filters)
|
||||
|
||||
def test_override_search_fields(self):
|
||||
class CustomSearchFilter(filters.SearchFilter):
|
||||
search_fields_property = 'nonstandard_search_fields'
|
||||
|
||||
|
||||
class SearchListView(generics.ListAPIView):
|
||||
queryset = SearchFilterModel.objects.all()
|
||||
serializer_class = SearchFilterSerializer
|
||||
filter_backends = (CustomSearchFilter,)
|
||||
nonstandard_search_fields = ('title', 'text')
|
||||
|
||||
view = SearchListView.as_view()
|
||||
request = factory.get('/', {'search': 'b'})
|
||||
response = view(request)
|
||||
self.assertEqual(
|
||||
response.data,
|
||||
[
|
||||
{'id': 1, 'title': 'z', 'text': 'abc'},
|
||||
{'id': 2, 'title': 'zz', 'text': 'bcd'}
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
class AttributeModel(models.Model):
|
||||
label = models.CharField(max_length=32)
|
||||
|
|
Loading…
Reference in New Issue
Block a user