| 1 |
""" |
| 2 |
Provides generic filtering backends that can be used to filter the results |
| 3 |
returned by list views. |
| 4 |
""" |
| 5 |
import operator |
| 6 |
from functools import reduce |
| 7 |
|
| 8 |
from django.core.exceptions import FieldDoesNotExist, ImproperlyConfigured |
| 9 |
from django.db import models |
| 10 |
from django.db.models.constants import LOOKUP_SEP |
| 11 |
from django.template import loader |
| 12 |
from django.utils.encoding import force_str |
| 13 |
from django.utils.text import smart_split, unescape_string_literal |
| 14 |
from django.utils.translation import gettext_lazy as _ |
| 15 |
|
| 16 |
from rest_framework.fields import CharField |
| 17 |
from rest_framework.settings import api_settings |
| 18 |
|
| 19 |
|
| 20 |
def search_smart_split(search_terms): |
| 21 |
"""Returns sanitized search terms as a list.""" |
| 22 |
split_terms = [] |
| 23 |
for term in smart_split(search_terms): |
| 24 |
# trim commas to avoid bad matching for quoted phrases |
| 25 |
term = term.strip(',') |
| 26 |
if term.startswith(('"', "'")) and term[0] == term[-1]: |
| 27 |
# quoted phrases are kept together without any other split |
| 28 |
split_terms.append(unescape_string_literal(term)) |
| 29 |
else: |
| 30 |
# non-quoted tokens are split by comma, keeping only non-empty ones |
| 31 |
for sub_term in term.split(','): |
| 32 |
if sub_term: |
| 33 |
split_terms.append(sub_term.strip()) |
| 34 |
return split_terms |
| 35 |
|
| 36 |
|
| 37 |
class BaseFilterBackend: |
| 38 |
""" |
| 39 |
A base class from which all filter backend classes should inherit. |
| 40 |
""" |
| 41 |
|
| 42 |
def filter_queryset(self, request, queryset, view): |
| 43 |
""" |
| 44 |
Return a filtered queryset. |
| 45 |
""" |
| 46 |
raise NotImplementedError(".filter_queryset() must be overridden.") |
| 47 |
|
| 48 |
def get_schema_operation_parameters(self, view): |
| 49 |
return [] |
| 50 |
|
| 51 |
|
| 52 |
class SearchFilter(BaseFilterBackend): |
| 53 |
# The URL query parameter used for the search. |
| 54 |
search_param = api_settings.SEARCH_PARAM |
| 55 |
template = 'rest_framework/filters/search.html' |
| 56 |
lookup_prefixes = { |
| 57 |
'^': 'istartswith', |
| 58 |
'=': 'iexact', |
| 59 |
'@': 'search', |
| 60 |
'$': 'iregex', |
| 61 |
} |
| 62 |
default_lookup = 'icontains' |
| 63 |
search_title = _('Search') |
| 64 |
search_description = _('A search term.') |
| 65 |
|
| 66 |
def get_search_fields(self, view, request): |
| 67 |
""" |
| 68 |
Search fields are obtained from the view, but the request is always |
| 69 |
passed to this method. Sub-classes can override this method to |
| 70 |
dynamically change the search fields based on request content. |
| 71 |
""" |
| 72 |
return getattr(view, 'search_fields', None) |
| 73 |
|
| 74 |
def get_search_terms(self, request): |
| 75 |
""" |
| 76 |
Search terms are set by a ?search=... query parameter, |
| 77 |
and may be whitespace delimited. |
| 78 |
""" |
| 79 |
value = request.query_params.get(self.search_param, '') |
| 80 |
field = CharField(trim_whitespace=False, allow_blank=True) |
| 81 |
cleaned_value = field.run_validation(value) |
| 82 |
return search_smart_split(cleaned_value) |
| 83 |
|
| 84 |
def construct_search(self, field_name, queryset): |
| 85 |
lookup = self.lookup_prefixes.get(field_name[0]) |
| 86 |
if lookup: |
| 87 |
field_name = field_name[1:] |
| 88 |
else: |
| 89 |
# Use field_name if it includes a lookup. |
| 90 |
opts = queryset.model._meta |
| 91 |
lookup_fields = field_name.split(LOOKUP_SEP) |
| 92 |
# Go through the fields, following all relations. |
| 93 |
prev_field = None |
| 94 |
for path_part in lookup_fields: |
| 95 |
if path_part == "pk": |
| 96 |
path_part = opts.pk.name |
| 97 |
try: |
| 98 |
field = opts.get_field(path_part) |
| 99 |
except FieldDoesNotExist: |
| 100 |
# Use valid query lookups. |
| 101 |
if prev_field and prev_field.get_lookup(path_part): |
| 102 |
return field_name |
| 103 |
else: |
| 104 |
prev_field = field |
| 105 |
if hasattr(field, "path_infos"): |
| 106 |
# Update opts to follow the relation. |
| 107 |
opts = field.path_infos[-1].to_opts |
| 108 |
# Otherwise, use the field with the default lookup. |
| 109 |
lookup = self.default_lookup |
| 110 |
return LOOKUP_SEP.join([field_name, lookup]) |
| 111 |
|
| 112 |
def must_call_distinct(self, queryset, search_fields): |
| 113 |
""" |
| 114 |
Return True if 'distinct()' should be used to query the given lookups. |
| 115 |
""" |
| 116 |
for search_field in search_fields: |
| 117 |
opts = queryset.model._meta |
| 118 |
if search_field[0] in self.lookup_prefixes: |
| 119 |
search_field = search_field[1:] |
| 120 |
# Annotated fields do not need to be distinct |
| 121 |
if isinstance(queryset, models.QuerySet) and search_field in queryset.query.annotations: |
| 122 |
continue |
| 123 |
parts = search_field.split(LOOKUP_SEP) |
| 124 |
for part in parts: |
| 125 |
field = opts.get_field(part) |
| 126 |
if hasattr(field, 'get_path_info'): |
| 127 |
# This field is a relation, update opts to follow the relation |
| 128 |
path_info = field.get_path_info() |
| 129 |
opts = path_info[-1].to_opts |
| 130 |
if any(path.m2m for path in path_info): |
| 131 |
# This field is a m2m relation so we know we need to call distinct |
| 132 |
return True |
| 133 |
else: |
| 134 |
# This field has a custom __ query transform but is not a relational field. |
| 135 |
break |
| 136 |
return False |
| 137 |
|
| 138 |
def filter_queryset(self, request, queryset, view): |
| 139 |
search_fields = self.get_search_fields(view, request) |
| 140 |
search_terms = self.get_search_terms(request) |
| 141 |
|
| 142 |
if not search_fields or not search_terms: |
| 143 |
return queryset |
| 144 |
|
| 145 |
orm_lookups = [ |
| 146 |
self.construct_search(str(search_field), queryset) |
| 147 |
for search_field in search_fields |
| 148 |
] |
| 149 |
|
| 150 |
base = queryset |
| 151 |
# generator which for each term builds the corresponding search |
| 152 |
conditions = ( |
| 153 |
reduce( |
| 154 |
operator.or_, |
| 155 |
(models.Q(**{orm_lookup: term}) for orm_lookup in orm_lookups) |
| 156 |
) for term in search_terms |
| 157 |
) |
| 158 |
queryset = queryset.filter(reduce(operator.and_, conditions)) |
| 159 |
|
| 160 |
# Remove duplicates from results, if necessary |
| 161 |
if self.must_call_distinct(queryset, search_fields): |
| 162 |
# inspired by django.contrib.admin |
| 163 |
# this is more accurate than .distinct form M2M relationship |
| 164 |
# also is cross-database |
| 165 |
queryset = queryset.filter(pk=models.OuterRef('pk')) |
| 166 |
queryset = base.filter(models.Exists(queryset)) |
| 167 |
return queryset |
| 168 |
|
| 169 |
def to_html(self, request, queryset, view): |
| 170 |
if not getattr(view, 'search_fields', None): |
| 171 |
return '' |
| 172 |
|
| 173 |
context = { |
| 174 |
'param': self.search_param, |
| 175 |
'term': request.query_params.get(self.search_param, ''), |
| 176 |
} |
| 177 |
template = loader.get_template(self.template) |
| 178 |
return template.render(context) |
| 179 |
|
| 180 |
def get_schema_operation_parameters(self, view): |
| 181 |
return [ |
| 182 |
{ |
| 183 |
'name': self.search_param, |
| 184 |
'required': False, |
| 185 |
'in': 'query', |
| 186 |
'description': force_str(self.search_description), |
| 187 |
'schema': { |
| 188 |
'type': 'string', |
| 189 |
}, |
| 190 |
}, |
| 191 |
] |
| 192 |
|
| 193 |
|
| 194 |
class UnaccentedSearchFilter(SearchFilter): |
| 195 |
""" |
| 196 |
A SearchFilter that performs accent-insensitive matching. |
| 197 |
|
| 198 |
Requires PostgreSQL with the ``unaccent`` extension installed and |
| 199 |
``django.contrib.postgres`` in ``INSTALLED_APPS``. See |
| 200 |
https://docs.djangoproject.com/en/stable/ref/contrib/postgres/lookups/#unaccent |
| 201 |
""" |
| 202 |
lookup_prefixes = { |
| 203 |
'^': 'unaccent__istartswith', |
| 204 |
'=': 'unaccent__iexact', |
| 205 |
# '@' stays accent-sensitive: unaccent can't be applied to full-text |
| 206 |
# search. |
| 207 |
'@': 'search', |
| 208 |
'$': 'unaccent__iregex', |
| 209 |
} |
| 210 |
default_lookup = 'unaccent__icontains' |
| 211 |
|
| 212 |
|
| 213 |
class OrderingFilter(BaseFilterBackend): |
| 214 |
# The URL query parameter used for the ordering. |
| 215 |
ordering_param = api_settings.ORDERING_PARAM |
| 216 |
ordering_fields = None |
| 217 |
ordering_title = _('Ordering') |
| 218 |
ordering_description = _('Which field to use when ordering the results.') |
| 219 |
template = 'rest_framework/filters/ordering.html' |
| 220 |
|
| 221 |
def get_ordering(self, request, queryset, view): |
| 222 |
""" |
| 223 |
Ordering is set by a comma delimited ?ordering=... query parameter. |
| 224 |
|
| 225 |
The `ordering` query parameter can be overridden by setting |
| 226 |
the `ordering_param` value on the OrderingFilter or by |
| 227 |
specifying an `ORDERING_PARAM` value in the API settings. |
| 228 |
""" |
| 229 |
params = request.query_params.get(self.ordering_param) |
| 230 |
if params: |
| 231 |
fields = [param.strip() for param in params.split(',')] |
| 232 |
ordering = self.remove_invalid_fields(queryset, fields, view, request) |
| 233 |
if ordering: |
| 234 |
return ordering |
| 235 |
|
| 236 |
# No ordering was included, or all the ordering fields were invalid |
| 237 |
return self.get_default_ordering(view) |
| 238 |
|
| 239 |
def get_default_ordering(self, view): |
| 240 |
ordering = getattr(view, 'ordering', None) |
| 241 |
if isinstance(ordering, str): |
| 242 |
return (ordering,) |
| 243 |
return ordering |
| 244 |
|
| 245 |
def get_default_valid_fields(self, queryset, view, context=None): |
| 246 |
if context is None: |
| 247 |
context = {} |
| 248 |
# If `ordering_fields` is not specified, then we determine a default |
| 249 |
# based on the serializer class, if one exists on the view. |
| 250 |
if hasattr(view, 'get_serializer_class'): |
| 251 |
try: |
| 252 |
serializer_class = view.get_serializer_class() |
| 253 |
except AssertionError: |
| 254 |
# Raised by the default implementation if |
| 255 |
# no serializer_class was found |
| 256 |
serializer_class = None |
| 257 |
else: |
| 258 |
serializer_class = getattr(view, 'serializer_class', None) |
| 259 |
|
| 260 |
if serializer_class is None: |
| 261 |
msg = ( |
| 262 |
"Cannot use %s on a view which does not have either a " |
| 263 |
"'serializer_class', an overriding 'get_serializer_class' " |
| 264 |
"or 'ordering_fields' attribute." |
| 265 |
) |
| 266 |
raise ImproperlyConfigured(msg % self.__class__.__name__) |
| 267 |
|
| 268 |
model_class = queryset.model |
| 269 |
model_property_names = [ |
| 270 |
# 'pk' is a property added in Django's Model class, however it is valid for ordering. |
| 271 |
attr for attr in dir(model_class) if isinstance(getattr(model_class, attr), property) and attr != 'pk' |
| 272 |
] |
| 273 |
|
| 274 |
return [ |
| 275 |
(field.source.replace('.', '__') or field_name, field.label) |
| 276 |
for field_name, field in serializer_class(context=context).fields.items() |
| 277 |
if ( |
| 278 |
not getattr(field, 'write_only', False) and |
| 279 |
not field.source == '*' and |
| 280 |
field.source not in model_property_names |
| 281 |
) |
| 282 |
] |
| 283 |
|
| 284 |
def get_valid_fields(self, queryset, view, context=None): |
| 285 |
if context is None: |
| 286 |
context = {} |
| 287 |
valid_fields = getattr(view, 'ordering_fields', self.ordering_fields) |
| 288 |
|
| 289 |
if valid_fields is None: |
| 290 |
# Default to allowing filtering on serializer fields |
| 291 |
return self.get_default_valid_fields(queryset, view, context) |
| 292 |
|
| 293 |
elif valid_fields == '__all__': |
| 294 |
# View explicitly allows filtering on any model field |
| 295 |
valid_fields = [ |
| 296 |
(field.name, field.verbose_name) for field in queryset.model._meta.fields |
| 297 |
] |
| 298 |
valid_fields += [ |
| 299 |
(key, key.title().split('__')) |
| 300 |
for key in queryset.query.annotations |
| 301 |
] |
| 302 |
else: |
| 303 |
valid_fields = [ |
| 304 |
(item, item) if isinstance(item, str) else item |
| 305 |
for item in valid_fields |
| 306 |
] |
| 307 |
|
| 308 |
return valid_fields |
| 309 |
|
| 310 |
def remove_invalid_fields(self, queryset, fields, view, request): |
| 311 |
valid_fields = [item[0] for item in self.get_valid_fields(queryset, view, {'request': request})] |
| 312 |
|
| 313 |
def term_valid(term): |
| 314 |
if term.startswith("-"): |
| 315 |
term = term[1:] |
| 316 |
return term in valid_fields |
| 317 |
|
| 318 |
return [term for term in fields if term_valid(term)] |
| 319 |
|
| 320 |
def filter_queryset(self, request, queryset, view): |
| 321 |
ordering = self.get_ordering(request, queryset, view) |
| 322 |
|
| 323 |
if ordering: |
| 324 |
return queryset.order_by(*ordering) |
| 325 |
|
| 326 |
return queryset |
| 327 |
|
| 328 |
def get_template_context(self, request, queryset, view): |
| 329 |
current = self.get_ordering(request, queryset, view) |
| 330 |
current = None if not current else current[0] |
| 331 |
options = [] |
| 332 |
context = { |
| 333 |
'request': request, |
| 334 |
'current': current, |
| 335 |
'param': self.ordering_param, |
| 336 |
} |
| 337 |
for key, label in self.get_valid_fields(queryset, view, context): |
| 338 |
options.append((key, '%s - %s' % (label, _('ascending')))) |
| 339 |
options.append(('-' + key, '%s - %s' % (label, _('descending')))) |
| 340 |
context['options'] = options |
| 341 |
return context |
| 342 |
|
| 343 |
def to_html(self, request, queryset, view): |
| 344 |
template = loader.get_template(self.template) |
| 345 |
context = self.get_template_context(request, queryset, view) |
| 346 |
return template.render(context) |
| 347 |
|
| 348 |
def get_schema_operation_parameters(self, view): |
| 349 |
return [ |
| 350 |
{ |
| 351 |
'name': self.ordering_param, |
| 352 |
'required': False, |
| 353 |
'in': 'query', |
| 354 |
'description': force_str(self.ordering_description), |
| 355 |
'schema': { |
| 356 |
'type': 'string', |
| 357 |
}, |
| 358 |
}, |
| 359 |
] |