| 1 |
from collections import OrderedDict |
| 2 |
from collections.abc import Iterable |
| 3 |
from datetime import timedelta |
| 4 |
from itertools import chain |
| 5 |
|
| 6 |
from django import forms |
| 7 |
from django.core.validators import MaxValueValidator |
| 8 |
from django.db.models import Q |
| 9 |
from django.db.models.constants import LOOKUP_SEP |
| 10 |
from django.forms.utils import pretty_name |
| 11 |
from django.utils.timezone import now |
| 12 |
from django.utils.translation import gettext_lazy as _ |
| 13 |
|
| 14 |
from .conf import settings |
| 15 |
from .constants import EMPTY_VALUES |
| 16 |
from .fields import ( |
| 17 |
BaseCSVField, |
| 18 |
BaseRangeField, |
| 19 |
ChoiceField, |
| 20 |
DateRangeField, |
| 21 |
DateTimeRangeField, |
| 22 |
IsoDateTimeField, |
| 23 |
IsoDateTimeRangeField, |
| 24 |
LookupChoiceField, |
| 25 |
ModelChoiceField, |
| 26 |
ModelMultipleChoiceField, |
| 27 |
MultipleChoiceField, |
| 28 |
RangeField, |
| 29 |
TimeRangeField, |
| 30 |
) |
| 31 |
from .utils import get_model_field, label_for_filter |
| 32 |
|
| 33 |
try: |
| 34 |
from django.utils.choices import normalize_choices |
| 35 |
except ImportError: |
| 36 |
DJANGO_50 = False |
| 37 |
else: |
| 38 |
DJANGO_50 = True |
| 39 |
|
| 40 |
|
| 41 |
__all__ = [ |
| 42 |
"AllValuesFilter", |
| 43 |
"AllValuesMultipleFilter", |
| 44 |
"BaseCSVFilter", |
| 45 |
"BaseInFilter", |
| 46 |
"BaseRangeFilter", |
| 47 |
"BooleanFilter", |
| 48 |
"CharFilter", |
| 49 |
"ChoiceFilter", |
| 50 |
"DateFilter", |
| 51 |
"DateFromToRangeFilter", |
| 52 |
"DateRangeFilter", |
| 53 |
"DateTimeFilter", |
| 54 |
"DateTimeFromToRangeFilter", |
| 55 |
"DurationFilter", |
| 56 |
"Filter", |
| 57 |
"IsoDateTimeFilter", |
| 58 |
"IsoDateTimeFromToRangeFilter", |
| 59 |
"LookupChoiceFilter", |
| 60 |
"ModelChoiceFilter", |
| 61 |
"ModelMultipleChoiceFilter", |
| 62 |
"MultipleChoiceFilter", |
| 63 |
"NumberFilter", |
| 64 |
"NumericRangeFilter", |
| 65 |
"OrderingFilter", |
| 66 |
"RangeFilter", |
| 67 |
"TimeFilter", |
| 68 |
"TimeRangeFilter", |
| 69 |
"TypedChoiceFilter", |
| 70 |
"TypedMultipleChoiceFilter", |
| 71 |
"UUIDFilter", |
| 72 |
] |
| 73 |
|
| 74 |
|
| 75 |
class Filter: |
| 76 |
creation_counter = 0 |
| 77 |
field_class = forms.Field |
| 78 |
|
| 79 |
def __init__( |
| 80 |
self, |
| 81 |
field_name=None, |
| 82 |
lookup_expr=None, |
| 83 |
*, |
| 84 |
label=None, |
| 85 |
method=None, |
| 86 |
distinct=False, |
| 87 |
exclude=False, |
| 88 |
**kwargs |
| 89 |
): |
| 90 |
if lookup_expr is None: |
| 91 |
lookup_expr = settings.DEFAULT_LOOKUP_EXPR |
| 92 |
self.field_name = field_name |
| 93 |
self.lookup_expr = lookup_expr |
| 94 |
self.label = label |
| 95 |
self.method = method |
| 96 |
self.distinct = distinct |
| 97 |
self.exclude = exclude |
| 98 |
|
| 99 |
self.extra = kwargs |
| 100 |
self.extra.setdefault("required", False) |
| 101 |
|
| 102 |
self.creation_counter = Filter.creation_counter |
| 103 |
Filter.creation_counter += 1 |
| 104 |
|
| 105 |
def get_method(self, qs): |
| 106 |
"""Return filter method based on whether we're excluding |
| 107 |
or simply filtering. |
| 108 |
""" |
| 109 |
return qs.exclude if self.exclude else qs.filter |
| 110 |
|
| 111 |
def method(): |
| 112 |
""" |
| 113 |
Filter method needs to be lazily resolved, as it may be dependent on |
| 114 |
the 'parent' FilterSet. |
| 115 |
""" |
| 116 |
|
| 117 |
def fget(self): |
| 118 |
return self._method |
| 119 |
|
| 120 |
def fset(self, value): |
| 121 |
self._method = value |
| 122 |
|
| 123 |
# clear existing FilterMethod |
| 124 |
if isinstance(self.filter, FilterMethod): |
| 125 |
del self.filter |
| 126 |
|
| 127 |
# override filter w/ FilterMethod. |
| 128 |
if value is not None: |
| 129 |
self.filter = FilterMethod(self) |
| 130 |
|
| 131 |
return locals() |
| 132 |
|
| 133 |
method = property(**method()) |
| 134 |
|
| 135 |
def label(): |
| 136 |
def fget(self): |
| 137 |
if self._label is None and hasattr(self, "model"): |
| 138 |
self._label = label_for_filter( |
| 139 |
self.model, self.field_name, self.lookup_expr, self.exclude |
| 140 |
) |
| 141 |
return self._label |
| 142 |
|
| 143 |
def fset(self, value): |
| 144 |
self._label = value |
| 145 |
|
| 146 |
return locals() |
| 147 |
|
| 148 |
label = property(**label()) |
| 149 |
|
| 150 |
@property |
| 151 |
def field(self): |
| 152 |
if not hasattr(self, "_field"): |
| 153 |
field_kwargs = self.extra.copy() |
| 154 |
|
| 155 |
if settings.DISABLE_HELP_TEXT: |
| 156 |
field_kwargs.pop("help_text", None) |
| 157 |
|
| 158 |
self._field = self.field_class(label=self.label, **field_kwargs) |
| 159 |
return self._field |
| 160 |
|
| 161 |
def filter(self, qs, value): |
| 162 |
if value in EMPTY_VALUES: |
| 163 |
return qs |
| 164 |
if self.distinct: |
| 165 |
qs = qs.distinct() |
| 166 |
lookup = "%s__%s" % (self.field_name, self.lookup_expr) |
| 167 |
qs = self.get_method(qs)(**{lookup: value}) |
| 168 |
return qs |
| 169 |
|
| 170 |
|
| 171 |
class CharFilter(Filter): |
| 172 |
field_class = forms.CharField |
| 173 |
|
| 174 |
|
| 175 |
class BooleanFilter(Filter): |
| 176 |
field_class = forms.NullBooleanField |
| 177 |
|
| 178 |
|
| 179 |
class ChoiceFilter(Filter): |
| 180 |
field_class = ChoiceField |
| 181 |
|
| 182 |
def __init__(self, *args, **kwargs): |
| 183 |
self.null_value = kwargs.get("null_value", settings.NULL_CHOICE_VALUE) |
| 184 |
super().__init__(*args, **kwargs) |
| 185 |
|
| 186 |
def filter(self, qs, value): |
| 187 |
if value != self.null_value: |
| 188 |
return super().filter(qs, value) |
| 189 |
|
| 190 |
qs = self.get_method(qs)( |
| 191 |
**{"%s__%s" % (self.field_name, self.lookup_expr): None} |
| 192 |
) |
| 193 |
return qs.distinct() if self.distinct else qs |
| 194 |
|
| 195 |
|
| 196 |
class TypedChoiceFilter(Filter): |
| 197 |
field_class = forms.TypedChoiceField |
| 198 |
|
| 199 |
|
| 200 |
class UUIDFilter(Filter): |
| 201 |
field_class = forms.UUIDField |
| 202 |
|
| 203 |
|
| 204 |
class MultipleChoiceFilter(Filter): |
| 205 |
""" |
| 206 |
This filter performs OR(by default) or AND(using conjoined=True) query |
| 207 |
on the selected options. |
| 208 |
|
| 209 |
Advanced usage |
| 210 |
-------------- |
| 211 |
Depending on your application logic, when all or no choices are selected, |
| 212 |
filtering may be a no-operation. In this case you may wish to avoid the |
| 213 |
filtering overhead, particularly if using a `distinct` call. |
| 214 |
|
| 215 |
You can override `get_filter_predicate` to use a custom filter. |
| 216 |
By default it will use the filter's name for the key, and the value will |
| 217 |
be the model object - or in case of passing in `to_field_name` the |
| 218 |
value of that attribute on the model. |
| 219 |
|
| 220 |
Set `always_filter` to `False` after instantiation to enable the default |
| 221 |
`is_noop` test. You can override `is_noop` if you need a different test |
| 222 |
for your application. |
| 223 |
|
| 224 |
`distinct` defaults to `True` as to-many relationships will generally |
| 225 |
require this. |
| 226 |
""" |
| 227 |
|
| 228 |
field_class = MultipleChoiceField |
| 229 |
|
| 230 |
always_filter = True |
| 231 |
|
| 232 |
def __init__(self, *args, **kwargs): |
| 233 |
kwargs.setdefault("distinct", True) |
| 234 |
self.conjoined = kwargs.pop("conjoined", False) |
| 235 |
self.null_value = kwargs.get("null_value", settings.NULL_CHOICE_VALUE) |
| 236 |
super().__init__(*args, **kwargs) |
| 237 |
|
| 238 |
def is_noop(self, qs, value): |
| 239 |
""" |
| 240 |
Return `True` to short-circuit unnecessary and potentially slow |
| 241 |
filtering. |
| 242 |
""" |
| 243 |
if self.always_filter: |
| 244 |
return False |
| 245 |
|
| 246 |
# A reasonable default for being a noop... |
| 247 |
if self.extra.get("required") and len(value) == len(self.field.choices): |
| 248 |
return True |
| 249 |
|
| 250 |
return False |
| 251 |
|
| 252 |
def filter(self, qs, value): |
| 253 |
if not value: |
| 254 |
# Even though not a noop, no point filtering if empty. |
| 255 |
return qs |
| 256 |
|
| 257 |
if self.is_noop(qs, value): |
| 258 |
return qs |
| 259 |
|
| 260 |
if not self.conjoined: |
| 261 |
q = Q() |
| 262 |
for v in set(value): |
| 263 |
if v == self.null_value: |
| 264 |
v = None |
| 265 |
predicate = self.get_filter_predicate(v) |
| 266 |
if self.conjoined: |
| 267 |
qs = self.get_method(qs)(**predicate) |
| 268 |
else: |
| 269 |
q |= Q(**predicate) |
| 270 |
|
| 271 |
if not self.conjoined: |
| 272 |
qs = self.get_method(qs)(q) |
| 273 |
|
| 274 |
return qs.distinct() if self.distinct else qs |
| 275 |
|
| 276 |
def get_filter_predicate(self, v): |
| 277 |
name = self.field_name |
| 278 |
if name and self.lookup_expr != settings.DEFAULT_LOOKUP_EXPR: |
| 279 |
name = LOOKUP_SEP.join([name, self.lookup_expr]) |
| 280 |
try: |
| 281 |
return {name: getattr(v, self.field.to_field_name)} |
| 282 |
except (AttributeError, TypeError): |
| 283 |
return {name: v} |
| 284 |
|
| 285 |
|
| 286 |
class TypedMultipleChoiceFilter(MultipleChoiceFilter): |
| 287 |
field_class = forms.TypedMultipleChoiceField |
| 288 |
|
| 289 |
|
| 290 |
class DateFilter(Filter): |
| 291 |
field_class = forms.DateField |
| 292 |
|
| 293 |
|
| 294 |
class DateTimeFilter(Filter): |
| 295 |
field_class = forms.DateTimeField |
| 296 |
|
| 297 |
|
| 298 |
class IsoDateTimeFilter(DateTimeFilter): |
| 299 |
""" |
| 300 |
Uses IsoDateTimeField to support filtering on ISO 8601 formatted datetimes. |
| 301 |
|
| 302 |
For context see: |
| 303 |
|
| 304 |
* https://code.djangoproject.com/ticket/23448 |
| 305 |
* https://github.com/encode/django-rest-framework/issues/1338 |
| 306 |
* https://github.com/carltongibson/django-filter/pull/264 |
| 307 |
""" |
| 308 |
|
| 309 |
field_class = IsoDateTimeField |
| 310 |
|
| 311 |
|
| 312 |
class TimeFilter(Filter): |
| 313 |
field_class = forms.TimeField |
| 314 |
|
| 315 |
|
| 316 |
class DurationFilter(Filter): |
| 317 |
field_class = forms.DurationField |
| 318 |
|
| 319 |
|
| 320 |
class QuerySetRequestMixin: |
| 321 |
""" |
| 322 |
Add callable functionality to filters that support the ``queryset`` |
| 323 |
argument. If the ``queryset`` is callable, then it **must** accept the |
| 324 |
``request`` object as a single argument. |
| 325 |
|
| 326 |
This is useful for filtering querysets by properties on the ``request`` |
| 327 |
object, such as the user. |
| 328 |
|
| 329 |
Example:: |
| 330 |
|
| 331 |
def departments(request): |
| 332 |
company = request.user.company |
| 333 |
return company.department_set.all() |
| 334 |
|
| 335 |
class EmployeeFilter(filters.FilterSet): |
| 336 |
department = filters.ModelChoiceFilter(queryset=departments) |
| 337 |
... |
| 338 |
|
| 339 |
The above example restricts the set of departments to those in the logged-in |
| 340 |
user's associated company. |
| 341 |
|
| 342 |
""" |
| 343 |
|
| 344 |
def __init__(self, *args, **kwargs): |
| 345 |
self.queryset = kwargs.get("queryset") |
| 346 |
super().__init__(*args, **kwargs) |
| 347 |
|
| 348 |
def get_request(self): |
| 349 |
try: |
| 350 |
return self.parent.request |
| 351 |
except AttributeError: |
| 352 |
return None |
| 353 |
|
| 354 |
def get_queryset(self, request): |
| 355 |
queryset = self.queryset |
| 356 |
|
| 357 |
if callable(queryset): |
| 358 |
return queryset(request) |
| 359 |
return queryset |
| 360 |
|
| 361 |
@property |
| 362 |
def field(self): |
| 363 |
request = self.get_request() |
| 364 |
queryset = self.get_queryset(request) |
| 365 |
|
| 366 |
if queryset is not None: |
| 367 |
self.extra["queryset"] = queryset |
| 368 |
|
| 369 |
return super().field |
| 370 |
|
| 371 |
|
| 372 |
class ModelChoiceFilter(QuerySetRequestMixin, ChoiceFilter): |
| 373 |
field_class = ModelChoiceField |
| 374 |
|
| 375 |
def __init__(self, *args, **kwargs): |
| 376 |
kwargs.setdefault("empty_label", settings.EMPTY_CHOICE_LABEL) |
| 377 |
super().__init__(*args, **kwargs) |
| 378 |
|
| 379 |
|
| 380 |
class ModelMultipleChoiceFilter(QuerySetRequestMixin, MultipleChoiceFilter): |
| 381 |
field_class = ModelMultipleChoiceField |
| 382 |
|
| 383 |
|
| 384 |
class NumberFilter(Filter): |
| 385 |
field_class = forms.DecimalField |
| 386 |
|
| 387 |
def get_max_validator(self): |
| 388 |
""" |
| 389 |
Return a MaxValueValidator for the field, or None to disable. |
| 390 |
""" |
| 391 |
return MaxValueValidator(1e50) |
| 392 |
|
| 393 |
@property |
| 394 |
def field(self): |
| 395 |
if not hasattr(self, "_field"): |
| 396 |
field = super().field |
| 397 |
max_validator = self.get_max_validator() |
| 398 |
if max_validator: |
| 399 |
field.validators.append(max_validator) |
| 400 |
|
| 401 |
self._field = field |
| 402 |
return self._field |
| 403 |
|
| 404 |
|
| 405 |
class NumericRangeFilter(Filter): |
| 406 |
field_class = RangeField |
| 407 |
|
| 408 |
def filter(self, qs, value): |
| 409 |
if value: |
| 410 |
if value.start is not None and value.stop is not None: |
| 411 |
value = (value.start, value.stop) |
| 412 |
elif value.start is not None: |
| 413 |
self.lookup_expr = "startswith" |
| 414 |
value = value.start |
| 415 |
elif value.stop is not None: |
| 416 |
self.lookup_expr = "endswith" |
| 417 |
value = value.stop |
| 418 |
|
| 419 |
return super().filter(qs, value) |
| 420 |
|
| 421 |
|
| 422 |
class RangeFilter(Filter): |
| 423 |
field_class = RangeField |
| 424 |
|
| 425 |
def filter(self, qs, value): |
| 426 |
if value: |
| 427 |
if value.start is not None and value.stop is not None: |
| 428 |
self.lookup_expr = "range" |
| 429 |
value = (value.start, value.stop) |
| 430 |
elif value.start is not None: |
| 431 |
self.lookup_expr = "gte" |
| 432 |
value = value.start |
| 433 |
elif value.stop is not None: |
| 434 |
self.lookup_expr = "lte" |
| 435 |
value = value.stop |
| 436 |
|
| 437 |
return super().filter(qs, value) |
| 438 |
|
| 439 |
|
| 440 |
def _truncate(dt): |
| 441 |
return dt.date() |
| 442 |
|
| 443 |
|
| 444 |
class DateRangeFilter(ChoiceFilter): |
| 445 |
choices = [ |
| 446 |
("today", _("Today")), |
| 447 |
("yesterday", _("Yesterday")), |
| 448 |
("week", _("Past 7 days")), |
| 449 |
("month", _("This month")), |
| 450 |
("year", _("This year")), |
| 451 |
] |
| 452 |
|
| 453 |
filters = { |
| 454 |
"today": lambda qs, name: qs.filter( |
| 455 |
**{ |
| 456 |
"%s__year" % name: now().year, |
| 457 |
"%s__month" % name: now().month, |
| 458 |
"%s__day" % name: now().day, |
| 459 |
} |
| 460 |
), |
| 461 |
"yesterday": lambda qs, name: qs.filter( |
| 462 |
**{ |
| 463 |
"%s__year" % name: (now() - timedelta(days=1)).year, |
| 464 |
"%s__month" % name: (now() - timedelta(days=1)).month, |
| 465 |
"%s__day" % name: (now() - timedelta(days=1)).day, |
| 466 |
} |
| 467 |
), |
| 468 |
"week": lambda qs, name: qs.filter( |
| 469 |
**{ |
| 470 |
"%s__gte" % name: _truncate(now() - timedelta(days=7)), |
| 471 |
"%s__lt" % name: _truncate(now() + timedelta(days=1)), |
| 472 |
} |
| 473 |
), |
| 474 |
"month": lambda qs, name: qs.filter( |
| 475 |
**{"%s__year" % name: now().year, "%s__month" % name: now().month} |
| 476 |
), |
| 477 |
"year": lambda qs, name: qs.filter( |
| 478 |
**{ |
| 479 |
"%s__year" % name: now().year, |
| 480 |
} |
| 481 |
), |
| 482 |
} |
| 483 |
|
| 484 |
def __init__(self, choices=None, filters=None, *args, **kwargs): |
| 485 |
if choices is not None: |
| 486 |
self.choices = choices |
| 487 |
if filters is not None: |
| 488 |
self.filters = filters |
| 489 |
|
| 490 |
if isinstance(self.choices, dict): |
| 491 |
if DJANGO_50: |
| 492 |
self.choices = normalize_choices(self.choices) |
| 493 |
else: |
| 494 |
raise ValueError("Django 5.0 or later is required for dict choices") |
| 495 |
|
| 496 |
all_choices = list( |
| 497 |
chain.from_iterable( |
| 498 |
[subchoice[0] for subchoice in choice[1]] |
| 499 |
if isinstance(choice[1], (list, tuple)) # This is an optgroup |
| 500 |
else [choice[0]] |
| 501 |
for choice in self.choices |
| 502 |
) |
| 503 |
) |
| 504 |
unique = set(all_choices) ^ set(self.filters) |
| 505 |
assert not unique, ( |
| 506 |
"Keys must be present in both 'choices' and 'filters'. Missing keys: " |
| 507 |
"'%s'" % ", ".join(sorted(unique)) |
| 508 |
) |
| 509 |
|
| 510 |
# null choice not relevant |
| 511 |
kwargs.setdefault("null_label", None) |
| 512 |
super().__init__(choices=self.choices, *args, **kwargs) |
| 513 |
|
| 514 |
def filter(self, qs, value): |
| 515 |
if not value: |
| 516 |
return qs |
| 517 |
|
| 518 |
assert value in self.filters |
| 519 |
|
| 520 |
qs = self.filters[value](qs, self.field_name) |
| 521 |
return qs.distinct() if self.distinct else qs |
| 522 |
|
| 523 |
|
| 524 |
class DateFromToRangeFilter(RangeFilter): |
| 525 |
field_class = DateRangeField |
| 526 |
|
| 527 |
|
| 528 |
class DateTimeFromToRangeFilter(RangeFilter): |
| 529 |
field_class = DateTimeRangeField |
| 530 |
|
| 531 |
|
| 532 |
class IsoDateTimeFromToRangeFilter(RangeFilter): |
| 533 |
field_class = IsoDateTimeRangeField |
| 534 |
|
| 535 |
|
| 536 |
class TimeRangeFilter(RangeFilter): |
| 537 |
field_class = TimeRangeField |
| 538 |
|
| 539 |
|
| 540 |
class AllValuesFilter(ChoiceFilter): |
| 541 |
@property |
| 542 |
def field(self): |
| 543 |
qs = self.model._default_manager.distinct() |
| 544 |
qs = qs.order_by(self.field_name).values_list(self.field_name, flat=True) |
| 545 |
self.extra["choices"] = [(o, o) for o in qs] |
| 546 |
return super().field |
| 547 |
|
| 548 |
|
| 549 |
class AllValuesMultipleFilter(MultipleChoiceFilter): |
| 550 |
@property |
| 551 |
def field(self): |
| 552 |
qs = self.model._default_manager.distinct() |
| 553 |
qs = qs.order_by(self.field_name).values_list(self.field_name, flat=True) |
| 554 |
self.extra["choices"] = [(o, o) for o in qs] |
| 555 |
return super().field |
| 556 |
|
| 557 |
|
| 558 |
class BaseCSVFilter(Filter): |
| 559 |
""" |
| 560 |
Base class for CSV type filters, such as IN and RANGE. |
| 561 |
""" |
| 562 |
|
| 563 |
base_field_class = BaseCSVField |
| 564 |
|
| 565 |
def __init__(self, *args, **kwargs): |
| 566 |
kwargs.setdefault("help_text", _("Multiple values may be separated by commas.")) |
| 567 |
super().__init__(*args, **kwargs) |
| 568 |
|
| 569 |
class ConcreteCSVField(self.base_field_class, self.field_class): |
| 570 |
pass |
| 571 |
|
| 572 |
ConcreteCSVField.__name__ = self._field_class_name( |
| 573 |
self.field_class, self.lookup_expr |
| 574 |
) |
| 575 |
|
| 576 |
self.field_class = ConcreteCSVField |
| 577 |
|
| 578 |
@classmethod |
| 579 |
def _field_class_name(cls, field_class, lookup_expr): |
| 580 |
""" |
| 581 |
Generate a suitable class name for the concrete field class. This is not |
| 582 |
completely reliable, as not all field class names are of the format |
| 583 |
<Type>Field. |
| 584 |
|
| 585 |
ex:: |
| 586 |
|
| 587 |
BaseCSVFilter._field_class_name(DateTimeField, 'year__in') |
| 588 |
|
| 589 |
returns 'DateTimeYearInField' |
| 590 |
|
| 591 |
""" |
| 592 |
# DateTimeField => DateTime |
| 593 |
type_name = field_class.__name__ |
| 594 |
if type_name.endswith("Field"): |
| 595 |
type_name = type_name[:-5] |
| 596 |
|
| 597 |
# year__in => YearIn |
| 598 |
parts = lookup_expr.split(LOOKUP_SEP) |
| 599 |
expression_name = "".join(p.capitalize() for p in parts) |
| 600 |
|
| 601 |
# DateTimeYearInField |
| 602 |
return str("%s%sField" % (type_name, expression_name)) |
| 603 |
|
| 604 |
|
| 605 |
class BaseInFilter(BaseCSVFilter): |
| 606 |
def __init__(self, *args, **kwargs): |
| 607 |
kwargs.setdefault("lookup_expr", "in") |
| 608 |
super().__init__(*args, **kwargs) |
| 609 |
|
| 610 |
|
| 611 |
class BaseRangeFilter(BaseCSVFilter): |
| 612 |
base_field_class = BaseRangeField |
| 613 |
|
| 614 |
def __init__(self, *args, **kwargs): |
| 615 |
kwargs.setdefault("lookup_expr", "range") |
| 616 |
super().__init__(*args, **kwargs) |
| 617 |
|
| 618 |
|
| 619 |
class LookupChoiceFilter(Filter): |
| 620 |
""" |
| 621 |
A combined filter that allows users to select the lookup expression from a dropdown. |
| 622 |
|
| 623 |
* ``lookup_choices`` is an optional argument that accepts multiple input |
| 624 |
formats, and is ultimately normalized as the choices used in the lookup |
| 625 |
dropdown. See ``.get_lookup_choices()`` for more information. |
| 626 |
|
| 627 |
* ``field_class`` is an optional argument that allows you to set the inner |
| 628 |
form field class used to validate the value. Default: ``forms.CharField`` |
| 629 |
|
| 630 |
ex:: |
| 631 |
|
| 632 |
price = django_filters.LookupChoiceFilter( |
| 633 |
field_class=forms.DecimalField, |
| 634 |
lookup_choices=[ |
| 635 |
('exact', 'Equals'), |
| 636 |
('gt', 'Greater than'), |
| 637 |
('lt', 'Less than'), |
| 638 |
] |
| 639 |
) |
| 640 |
|
| 641 |
""" |
| 642 |
|
| 643 |
field_class = forms.CharField |
| 644 |
outer_class = LookupChoiceField |
| 645 |
|
| 646 |
def __init__( |
| 647 |
self, field_name=None, lookup_choices=None, field_class=None, **kwargs |
| 648 |
): |
| 649 |
self.empty_label = kwargs.pop("empty_label", settings.EMPTY_CHOICE_LABEL) |
| 650 |
|
| 651 |
super(LookupChoiceFilter, self).__init__(field_name=field_name, **kwargs) |
| 652 |
|
| 653 |
self.lookup_choices = lookup_choices |
| 654 |
if field_class is not None: |
| 655 |
self.field_class = field_class |
| 656 |
|
| 657 |
@classmethod |
| 658 |
def normalize_lookup(cls, lookup): |
| 659 |
""" |
| 660 |
Normalize the lookup into a tuple of ``(lookup expression, display value)`` |
| 661 |
|
| 662 |
If the ``lookup`` is already a tuple, the tuple is not altered. |
| 663 |
If the ``lookup`` is a string, a tuple is returned with the lookup |
| 664 |
expression used as the basis for the display value. |
| 665 |
|
| 666 |
ex:: |
| 667 |
|
| 668 |
>>> LookupChoiceFilter.normalize_lookup(('exact', 'Equals')) |
| 669 |
('exact', 'Equals') |
| 670 |
|
| 671 |
>>> LookupChoiceFilter.normalize_lookup('has_key') |
| 672 |
('has_key', 'Has key') |
| 673 |
|
| 674 |
""" |
| 675 |
if isinstance(lookup, str): |
| 676 |
return (lookup, pretty_name(lookup)) |
| 677 |
return (lookup[0], lookup[1]) |
| 678 |
|
| 679 |
def get_lookup_choices(self): |
| 680 |
""" |
| 681 |
Get the lookup choices in a format suitable for ``django.forms.ChoiceField``. |
| 682 |
If the filter is initialized with ``lookup_choices``, this value is normalized |
| 683 |
and passed to the underlying ``LookupChoiceField``. If no choices are provided, |
| 684 |
they are generated from the corresponding model field's registered lookups. |
| 685 |
""" |
| 686 |
lookups = self.lookup_choices |
| 687 |
if lookups is None: |
| 688 |
field = get_model_field(self.model, self.field_name) |
| 689 |
lookups = field.get_lookups() |
| 690 |
|
| 691 |
return [self.normalize_lookup(lookup) for lookup in lookups] |
| 692 |
|
| 693 |
@property |
| 694 |
def field(self): |
| 695 |
if not hasattr(self, "_field"): |
| 696 |
inner_field = super().field |
| 697 |
lookups = self.get_lookup_choices() |
| 698 |
|
| 699 |
self._field = self.outer_class( |
| 700 |
inner_field, |
| 701 |
lookups, |
| 702 |
label=self.label, |
| 703 |
empty_label=self.empty_label, |
| 704 |
required=self.extra["required"], |
| 705 |
) |
| 706 |
|
| 707 |
return self._field |
| 708 |
|
| 709 |
def filter(self, qs, lookup): |
| 710 |
if not lookup: |
| 711 |
return super().filter(qs, None) |
| 712 |
|
| 713 |
self.lookup_expr = lookup.lookup_expr |
| 714 |
return super().filter(qs, lookup.value) |
| 715 |
|
| 716 |
|
| 717 |
class OrderingFilter(BaseCSVFilter, ChoiceFilter): |
| 718 |
""" |
| 719 |
Enable queryset ordering. As an extension of ``ChoiceFilter`` it accepts |
| 720 |
two additional arguments that are used to build the ordering choices. |
| 721 |
|
| 722 |
* ``fields`` is a mapping of {model field name: parameter name}. The |
| 723 |
parameter names are exposed in the choices and mask/alias the field |
| 724 |
names used in the ``order_by()`` call. Similar to field ``choices``, |
| 725 |
``fields`` accepts the 'list of two-tuples' syntax that retains order. |
| 726 |
``fields`` may also just be an iterable of strings. In this case, the |
| 727 |
field names simply double as the exposed parameter names. |
| 728 |
|
| 729 |
* ``field_labels`` is an optional argument that allows you to customize |
| 730 |
the display label for the corresponding parameter. It accepts a mapping |
| 731 |
of {field name: human readable label}. Keep in mind that the key is the |
| 732 |
field name, and not the exposed parameter name. |
| 733 |
|
| 734 |
Additionally, you can just provide your own ``choices`` if you require |
| 735 |
explicit control over the exposed options. For example, when you might |
| 736 |
want to disable descending sort options. |
| 737 |
|
| 738 |
This filter is also CSV-based, and accepts multiple ordering params. The |
| 739 |
default select widget does not enable the use of this, but it is useful |
| 740 |
for APIs. |
| 741 |
|
| 742 |
""" |
| 743 |
|
| 744 |
descending_fmt = _("%s (descending)") |
| 745 |
|
| 746 |
def __init__(self, *args, **kwargs): |
| 747 |
""" |
| 748 |
``fields`` may be either a mapping or an iterable. |
| 749 |
``field_labels`` must be a map of field names to display labels |
| 750 |
""" |
| 751 |
fields = kwargs.pop("fields", {}) |
| 752 |
fields = self.normalize_fields(fields) |
| 753 |
field_labels = kwargs.pop("field_labels", {}) |
| 754 |
|
| 755 |
self.param_map = {v: k for k, v in fields.items()} |
| 756 |
|
| 757 |
if "choices" not in kwargs: |
| 758 |
kwargs["choices"] = self.build_choices(fields, field_labels) |
| 759 |
|
| 760 |
kwargs.setdefault("label", _("Ordering")) |
| 761 |
kwargs.setdefault("help_text", "") |
| 762 |
kwargs.setdefault("null_label", None) |
| 763 |
super().__init__(*args, **kwargs) |
| 764 |
|
| 765 |
def get_ordering_value(self, param): |
| 766 |
descending = param.startswith("-") |
| 767 |
param = param[1:] if descending else param |
| 768 |
field_name = self.param_map.get(param, param) |
| 769 |
|
| 770 |
return "-%s" % field_name if descending else field_name |
| 771 |
|
| 772 |
def filter(self, qs, value): |
| 773 |
if value in EMPTY_VALUES: |
| 774 |
return qs |
| 775 |
|
| 776 |
ordering = [ |
| 777 |
self.get_ordering_value(param) |
| 778 |
for param in value |
| 779 |
if param not in EMPTY_VALUES |
| 780 |
] |
| 781 |
return qs.order_by(*ordering) |
| 782 |
|
| 783 |
@classmethod |
| 784 |
def normalize_fields(cls, fields): |
| 785 |
""" |
| 786 |
Normalize the fields into an ordered map of {field name: param name} |
| 787 |
""" |
| 788 |
# fields is a mapping, copy into new OrderedDict |
| 789 |
if isinstance(fields, dict): |
| 790 |
return OrderedDict(fields) |
| 791 |
|
| 792 |
# convert iterable of values => iterable of pairs (field name, param name) |
| 793 |
assert isinstance( |
| 794 |
fields, Iterable |
| 795 |
), "'fields' must be an iterable (e.g., a list, tuple, or mapping)." |
| 796 |
|
| 797 |
# fields is an iterable of field names |
| 798 |
assert all( |
| 799 |
isinstance(field, str) |
| 800 |
or isinstance(field, Iterable) |
| 801 |
and len(field) == 2 # may need to be wrapped in parens |
| 802 |
for field in fields |
| 803 |
), "'fields' must contain strings or (field name, param name) pairs." |
| 804 |
|
| 805 |
return OrderedDict([(f, f) if isinstance(f, str) else f for f in fields]) |
| 806 |
|
| 807 |
def build_choices(self, fields, labels): |
| 808 |
ascending = [ |
| 809 |
(param, labels.get(field, _(pretty_name(param)))) |
| 810 |
for field, param in fields.items() |
| 811 |
] |
| 812 |
descending = [ |
| 813 |
("-%s" % param, labels.get("-%s" % param, self.descending_fmt % label)) |
| 814 |
for param, label in ascending |
| 815 |
] |
| 816 |
|
| 817 |
# interleave the ascending and descending choices |
| 818 |
return [val for pair in zip(ascending, descending) for val in pair] |
| 819 |
|
| 820 |
|
| 821 |
class FilterMethod: |
| 822 |
""" |
| 823 |
This helper is used to override Filter.filter() when a 'method' argument |
| 824 |
is passed. It proxies the call to the actual method on the filter's parent. |
| 825 |
""" |
| 826 |
|
| 827 |
def __init__(self, filter_instance): |
| 828 |
self.f = filter_instance |
| 829 |
|
| 830 |
def __call__(self, qs, value): |
| 831 |
if value in EMPTY_VALUES: |
| 832 |
return qs |
| 833 |
|
| 834 |
return self.method(qs, self.f.field_name, value) |
| 835 |
|
| 836 |
@property |
| 837 |
def method(self): |
| 838 |
""" |
| 839 |
Resolve the method on the parent filterset. |
| 840 |
""" |
| 841 |
instance = self.f |
| 842 |
|
| 843 |
# noop if 'method' is a function |
| 844 |
if callable(instance.method): |
| 845 |
return instance.method |
| 846 |
|
| 847 |
# otherwise, method is the name of a method on the parent FilterSet. |
| 848 |
assert hasattr( |
| 849 |
instance, "parent" |
| 850 |
), "Filter '%s' must have a parent FilterSet to find '.%s()'" % ( |
| 851 |
instance.field_name, |
| 852 |
instance.method, |
| 853 |
) |
| 854 |
|
| 855 |
parent = instance.parent |
| 856 |
method = getattr(parent, instance.method, None) |
| 857 |
|
| 858 |
assert callable( |
| 859 |
method |
| 860 |
), "Expected parent FilterSet '%s.%s' to have a '.%s()' method." % ( |
| 861 |
parent.__class__.__module__, |
| 862 |
parent.__class__.__name__, |
| 863 |
instance.method, |
| 864 |
) |
| 865 |
|
| 866 |
return method |