mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-08-08 06:14:47 +03:00
Refactored SearchFilter lookup prefixes.
This commit is contained in:
parent
1ada749a42
commit
93897b90ee
|
@ -133,6 +133,12 @@ class SearchFilter(BaseFilterBackend):
|
||||||
# The URL query parameter used for the search.
|
# The URL query parameter used for the search.
|
||||||
search_param = api_settings.SEARCH_PARAM
|
search_param = api_settings.SEARCH_PARAM
|
||||||
template = 'rest_framework/filters/search.html'
|
template = 'rest_framework/filters/search.html'
|
||||||
|
lookup_prefixes = {
|
||||||
|
'^': 'istartswith',
|
||||||
|
'=': 'iexact',
|
||||||
|
'@': 'search',
|
||||||
|
'$': 'iregex',
|
||||||
|
}
|
||||||
|
|
||||||
def get_search_terms(self, request):
|
def get_search_terms(self, request):
|
||||||
"""
|
"""
|
||||||
|
@ -143,23 +149,19 @@ class SearchFilter(BaseFilterBackend):
|
||||||
return params.replace(',', ' ').split()
|
return params.replace(',', ' ').split()
|
||||||
|
|
||||||
def construct_search(self, field_name):
|
def construct_search(self, field_name):
|
||||||
if field_name.startswith('^'):
|
lookup = self.lookup_prefixes.get(field_name[0])
|
||||||
return "%s__istartswith" % field_name[1:]
|
if lookup:
|
||||||
elif field_name.startswith('='):
|
field_name = field_name[1:]
|
||||||
return "%s__iexact" % field_name[1:]
|
|
||||||
elif field_name.startswith('@'):
|
|
||||||
return "%s__search" % field_name[1:]
|
|
||||||
if field_name.startswith('$'):
|
|
||||||
return "%s__iregex" % field_name[1:]
|
|
||||||
else:
|
else:
|
||||||
return "%s__icontains" % field_name
|
lookup = 'icontains'
|
||||||
|
return LOOKUP_SEP.join([field_name, lookup])
|
||||||
|
|
||||||
def must_call_distinct(self, opts, lookups):
|
def must_call_distinct(self, opts, lookups):
|
||||||
"""
|
"""
|
||||||
Return True if 'distinct()' should be used to query the given lookups.
|
Return True if 'distinct()' should be used to query the given lookups.
|
||||||
"""
|
"""
|
||||||
for lookup in lookups:
|
for lookup in lookups:
|
||||||
if lookup[0] in {'^', '=', '@', '$'}:
|
if lookup[0] in self.lookup_prefixes:
|
||||||
lookup = lookup[1:]
|
lookup = lookup[1:]
|
||||||
parts = lookup.split(LOOKUP_SEP)
|
parts = lookup.split(LOOKUP_SEP)
|
||||||
for part in parts:
|
for part in parts:
|
||||||
|
|
|
@ -499,7 +499,7 @@ class SearchFilterM2MTests(TestCase):
|
||||||
|
|
||||||
def test_must_call_distinct(self):
|
def test_must_call_distinct(self):
|
||||||
filter_ = filters.SearchFilter()
|
filter_ = filters.SearchFilter()
|
||||||
prefixes = ['', '^', '=', '@', '$']
|
prefixes = [''] + list(filter_.lookup_prefixes)
|
||||||
for prefix in prefixes:
|
for prefix in prefixes:
|
||||||
self.assertFalse(
|
self.assertFalse(
|
||||||
filter_.must_call_distinct(
|
filter_.must_call_distinct(
|
||||||
|
|
Loading…
Reference in New Issue
Block a user