| 1 |
""" |
| 2 |
This encapsulates the logic for displaying filters in the Django admin. |
| 3 |
Filters are specified in models with the "list_filter" option. |
| 4 |
|
| 5 |
Each filter subclass knows how to display a filter for a field that passes a |
| 6 |
certain test -- e.g. being a DateField or ForeignKey. |
| 7 |
""" |
| 8 |
|
| 9 |
import datetime |
| 10 |
|
| 11 |
from django.contrib.admin.exceptions import NotRegistered |
| 12 |
from django.contrib.admin.options import IncorrectLookupParameters |
| 13 |
from django.contrib.admin.utils import ( |
| 14 |
build_q_object_from_lookup_parameters, |
| 15 |
get_last_value_from_parameters, |
| 16 |
get_model_from_relation, |
| 17 |
prepare_lookup_value, |
| 18 |
reverse_field_path, |
| 19 |
) |
| 20 |
from django.core.exceptions import ImproperlyConfigured, ValidationError |
| 21 |
from django.db import models |
| 22 |
from django.utils import timezone |
| 23 |
from django.utils.translation import gettext_lazy as _ |
| 24 |
|
| 25 |
|
| 26 |
class ListFilter: |
| 27 |
title = None # Human-readable title to appear in the right sidebar. |
| 28 |
template = "admin/filter.html" |
| 29 |
|
| 30 |
def __init__(self, request, params, model, model_admin): |
| 31 |
self.request = request |
| 32 |
# This dictionary will eventually contain the request's query string |
| 33 |
# parameters actually used by this filter. |
| 34 |
self.used_parameters = {} |
| 35 |
if self.title is None: |
| 36 |
raise ImproperlyConfigured( |
| 37 |
"The list filter '%s' does not specify a 'title'." |
| 38 |
% self.__class__.__name__ |
| 39 |
) |
| 40 |
|
| 41 |
def has_output(self): |
| 42 |
""" |
| 43 |
Return True if some choices would be output for this filter. |
| 44 |
""" |
| 45 |
raise NotImplementedError( |
| 46 |
"subclasses of ListFilter must provide a has_output() method" |
| 47 |
) |
| 48 |
|
| 49 |
def choices(self, changelist): |
| 50 |
""" |
| 51 |
Return choices ready to be output in the template. |
| 52 |
|
| 53 |
`changelist` is the ChangeList to be displayed. |
| 54 |
""" |
| 55 |
raise NotImplementedError( |
| 56 |
"subclasses of ListFilter must provide a choices() method" |
| 57 |
) |
| 58 |
|
| 59 |
def queryset(self, request, queryset): |
| 60 |
""" |
| 61 |
Return the filtered queryset. |
| 62 |
""" |
| 63 |
raise NotImplementedError( |
| 64 |
"subclasses of ListFilter must provide a queryset() method" |
| 65 |
) |
| 66 |
|
| 67 |
def expected_parameters(self): |
| 68 |
""" |
| 69 |
Return the list of parameter names that are expected from the |
| 70 |
request's query string and that will be used by this filter. |
| 71 |
""" |
| 72 |
raise NotImplementedError( |
| 73 |
"subclasses of ListFilter must provide an expected_parameters() method" |
| 74 |
) |
| 75 |
|
| 76 |
|
| 77 |
class FacetsMixin: |
| 78 |
def get_facet_counts(self, pk_attname, filtered_qs): |
| 79 |
raise NotImplementedError( |
| 80 |
"subclasses of FacetsMixin must provide a get_facet_counts() method." |
| 81 |
) |
| 82 |
|
| 83 |
def get_facet_queryset(self, changelist): |
| 84 |
filtered_qs = changelist.get_queryset( |
| 85 |
self.request, exclude_parameters=self.expected_parameters() |
| 86 |
) |
| 87 |
return filtered_qs.aggregate( |
| 88 |
**self.get_facet_counts(changelist.pk_attname, filtered_qs) |
| 89 |
) |
| 90 |
|
| 91 |
|
| 92 |
class SimpleListFilter(FacetsMixin, ListFilter): |
| 93 |
# The parameter that should be used in the query string for that filter. |
| 94 |
parameter_name = None |
| 95 |
|
| 96 |
def __init__(self, request, params, model, model_admin): |
| 97 |
super().__init__(request, params, model, model_admin) |
| 98 |
if self.parameter_name is None: |
| 99 |
raise ImproperlyConfigured( |
| 100 |
"The list filter '%s' does not specify a 'parameter_name'." |
| 101 |
% self.__class__.__name__ |
| 102 |
) |
| 103 |
if self.parameter_name in params: |
| 104 |
value = params.pop(self.parameter_name) |
| 105 |
self.used_parameters[self.parameter_name] = value[-1] |
| 106 |
lookup_choices = self.lookups(request, model_admin) |
| 107 |
if lookup_choices is None: |
| 108 |
lookup_choices = () |
| 109 |
self.lookup_choices = list(lookup_choices) |
| 110 |
|
| 111 |
def has_output(self): |
| 112 |
return len(self.lookup_choices) > 0 |
| 113 |
|
| 114 |
def value(self): |
| 115 |
""" |
| 116 |
Return the value (in string format) provided in the request's |
| 117 |
query string for this filter, if any, or None if the value wasn't |
| 118 |
provided. |
| 119 |
""" |
| 120 |
return self.used_parameters.get(self.parameter_name) |
| 121 |
|
| 122 |
def lookups(self, request, model_admin): |
| 123 |
""" |
| 124 |
Must be overridden to return a list of tuples (value, verbose value) |
| 125 |
""" |
| 126 |
raise NotImplementedError( |
| 127 |
"The SimpleListFilter.lookups() method must be overridden to " |
| 128 |
"return a list of tuples (value, verbose value)." |
| 129 |
) |
| 130 |
|
| 131 |
def expected_parameters(self): |
| 132 |
return [self.parameter_name] |
| 133 |
|
| 134 |
def get_facet_counts(self, pk_attname, filtered_qs): |
| 135 |
original_value = self.used_parameters.get(self.parameter_name) |
| 136 |
counts = {} |
| 137 |
for i, choice in enumerate(self.lookup_choices): |
| 138 |
self.used_parameters[self.parameter_name] = choice[0] |
| 139 |
lookup_qs = self.queryset(self.request, filtered_qs) |
| 140 |
if lookup_qs is not None: |
| 141 |
counts[f"{i}__c"] = models.Count( |
| 142 |
pk_attname, |
| 143 |
filter=models.Q(pk__in=lookup_qs), |
| 144 |
) |
| 145 |
self.used_parameters[self.parameter_name] = original_value |
| 146 |
return counts |
| 147 |
|
| 148 |
def choices(self, changelist): |
| 149 |
add_facets = changelist.add_facets |
| 150 |
facet_counts = self.get_facet_queryset(changelist) if add_facets else None |
| 151 |
yield { |
| 152 |
"selected": self.value() is None, |
| 153 |
"query_string": changelist.get_query_string(remove=[self.parameter_name]), |
| 154 |
"display": _("All"), |
| 155 |
} |
| 156 |
for i, (lookup, title) in enumerate(self.lookup_choices): |
| 157 |
if add_facets: |
| 158 |
if (count := facet_counts.get(f"{i}__c", -1)) != -1: |
| 159 |
title = f"{title} ({count})" |
| 160 |
else: |
| 161 |
title = f"{title} (-)" |
| 162 |
yield { |
| 163 |
"selected": self.value() == str(lookup), |
| 164 |
"query_string": changelist.get_query_string( |
| 165 |
{self.parameter_name: lookup} |
| 166 |
), |
| 167 |
"display": title, |
| 168 |
} |
| 169 |
|
| 170 |
|
| 171 |
class FieldListFilter(FacetsMixin, ListFilter): |
| 172 |
_field_list_filters = [] |
| 173 |
_take_priority_index = 0 |
| 174 |
list_separator = "," |
| 175 |
|
| 176 |
def __init__(self, field, request, params, model, model_admin, field_path): |
| 177 |
self.field = field |
| 178 |
self.field_path = field_path |
| 179 |
self.title = getattr(field, "verbose_name", field_path) |
| 180 |
super().__init__(request, params, model, model_admin) |
| 181 |
for p in self.expected_parameters(): |
| 182 |
if p in params: |
| 183 |
value = params.pop(p) |
| 184 |
self.used_parameters[p] = prepare_lookup_value( |
| 185 |
p, value, self.list_separator |
| 186 |
) |
| 187 |
|
| 188 |
def has_output(self): |
| 189 |
return True |
| 190 |
|
| 191 |
def queryset(self, request, queryset): |
| 192 |
try: |
| 193 |
q_object = build_q_object_from_lookup_parameters(self.used_parameters) |
| 194 |
return queryset.filter(q_object) |
| 195 |
except (ValueError, ValidationError) as e: |
| 196 |
# Fields may raise a ValueError or ValidationError when converting |
| 197 |
# the parameters to the correct type. |
| 198 |
raise IncorrectLookupParameters(e) |
| 199 |
|
| 200 |
@classmethod |
| 201 |
def register(cls, test, list_filter_class, take_priority=False): |
| 202 |
if take_priority: |
| 203 |
# This is to allow overriding the default filters for certain types |
| 204 |
# of fields with some custom filters. The first found in the list |
| 205 |
# is used in priority. |
| 206 |
cls._field_list_filters.insert( |
| 207 |
cls._take_priority_index, (test, list_filter_class) |
| 208 |
) |
| 209 |
cls._take_priority_index += 1 |
| 210 |
else: |
| 211 |
cls._field_list_filters.append((test, list_filter_class)) |
| 212 |
|
| 213 |
@classmethod |
| 214 |
def create(cls, field, request, params, model, model_admin, field_path): |
| 215 |
for test, list_filter_class in cls._field_list_filters: |
| 216 |
if test(field): |
| 217 |
return list_filter_class( |
| 218 |
field, request, params, model, model_admin, field_path=field_path |
| 219 |
) |
| 220 |
|
| 221 |
|
| 222 |
class RelatedFieldListFilter(FieldListFilter): |
| 223 |
def __init__(self, field, request, params, model, model_admin, field_path): |
| 224 |
other_model = get_model_from_relation(field) |
| 225 |
self.lookup_kwarg = "%s__%s__exact" % (field_path, field.target_field.name) |
| 226 |
self.lookup_kwarg_isnull = "%s__isnull" % field_path |
| 227 |
self.lookup_val = params.get(self.lookup_kwarg) |
| 228 |
self.lookup_val_isnull = get_last_value_from_parameters( |
| 229 |
params, self.lookup_kwarg_isnull |
| 230 |
) |
| 231 |
super().__init__(field, request, params, model, model_admin, field_path) |
| 232 |
self.lookup_choices = self.field_choices(field, request, model_admin) |
| 233 |
if hasattr(field, "verbose_name"): |
| 234 |
self.lookup_title = field.verbose_name |
| 235 |
else: |
| 236 |
self.lookup_title = other_model._meta.verbose_name |
| 237 |
self.title = self.lookup_title |
| 238 |
self.empty_value_display = model_admin.get_empty_value_display() |
| 239 |
|
| 240 |
@property |
| 241 |
def include_empty_choice(self): |
| 242 |
""" |
| 243 |
Return True if a "(None)" choice should be included, which filters |
| 244 |
out everything except empty relationships. |
| 245 |
""" |
| 246 |
return self.field.null or (self.field.is_relation and self.field.many_to_many) |
| 247 |
|
| 248 |
def has_output(self): |
| 249 |
if self.include_empty_choice: |
| 250 |
extra = 1 |
| 251 |
else: |
| 252 |
extra = 0 |
| 253 |
return len(self.lookup_choices) + extra > 1 |
| 254 |
|
| 255 |
def expected_parameters(self): |
| 256 |
return [self.lookup_kwarg, self.lookup_kwarg_isnull] |
| 257 |
|
| 258 |
def field_admin_ordering(self, field, request, model_admin): |
| 259 |
""" |
| 260 |
Return the model admin's ordering for related field, if provided. |
| 261 |
""" |
| 262 |
try: |
| 263 |
related_admin = model_admin.admin_site.get_model_admin( |
| 264 |
field.remote_field.model |
| 265 |
) |
| 266 |
except NotRegistered: |
| 267 |
return () |
| 268 |
else: |
| 269 |
return related_admin.get_ordering(request) |
| 270 |
|
| 271 |
def field_choices(self, field, request, model_admin): |
| 272 |
ordering = self.field_admin_ordering(field, request, model_admin) |
| 273 |
return field.get_choices(include_blank=False, ordering=ordering) |
| 274 |
|
| 275 |
def get_facet_counts(self, pk_attname, filtered_qs): |
| 276 |
counts = { |
| 277 |
f"{pk_val}__c": models.Count( |
| 278 |
pk_attname, filter=models.Q(**{self.lookup_kwarg: pk_val}) |
| 279 |
) |
| 280 |
for pk_val, _ in self.lookup_choices |
| 281 |
} |
| 282 |
if self.include_empty_choice: |
| 283 |
counts["__c"] = models.Count( |
| 284 |
pk_attname, filter=models.Q(**{self.lookup_kwarg_isnull: True}) |
| 285 |
) |
| 286 |
return counts |
| 287 |
|
| 288 |
def choices(self, changelist): |
| 289 |
add_facets = changelist.add_facets |
| 290 |
facet_counts = self.get_facet_queryset(changelist) if add_facets else None |
| 291 |
yield { |
| 292 |
"selected": self.lookup_val is None and not self.lookup_val_isnull, |
| 293 |
"query_string": changelist.get_query_string( |
| 294 |
remove=[self.lookup_kwarg, self.lookup_kwarg_isnull] |
| 295 |
), |
| 296 |
"display": _("All"), |
| 297 |
} |
| 298 |
count = None |
| 299 |
for pk_val, val in self.lookup_choices: |
| 300 |
if add_facets: |
| 301 |
count = facet_counts[f"{pk_val}__c"] |
| 302 |
val = f"{val} ({count})" |
| 303 |
yield { |
| 304 |
"selected": self.lookup_val is not None |
| 305 |
and str(pk_val) in self.lookup_val, |
| 306 |
"query_string": changelist.get_query_string( |
| 307 |
{self.lookup_kwarg: pk_val}, [self.lookup_kwarg_isnull] |
| 308 |
), |
| 309 |
"display": val, |
| 310 |
} |
| 311 |
empty_title = self.empty_value_display |
| 312 |
if self.include_empty_choice: |
| 313 |
if add_facets: |
| 314 |
count = facet_counts["__c"] |
| 315 |
empty_title = f"{empty_title} ({count})" |
| 316 |
yield { |
| 317 |
"selected": bool(self.lookup_val_isnull), |
| 318 |
"query_string": changelist.get_query_string( |
| 319 |
{self.lookup_kwarg_isnull: "True"}, [self.lookup_kwarg] |
| 320 |
), |
| 321 |
"display": empty_title, |
| 322 |
} |
| 323 |
|
| 324 |
|
| 325 |
FieldListFilter.register(lambda f: f.remote_field, RelatedFieldListFilter) |
| 326 |
|
| 327 |
|
| 328 |
class BooleanFieldListFilter(FieldListFilter): |
| 329 |
def __init__(self, field, request, params, model, model_admin, field_path): |
| 330 |
self.lookup_kwarg = "%s__exact" % field_path |
| 331 |
self.lookup_kwarg2 = "%s__isnull" % field_path |
| 332 |
self.lookup_val = get_last_value_from_parameters(params, self.lookup_kwarg) |
| 333 |
self.lookup_val2 = get_last_value_from_parameters(params, self.lookup_kwarg2) |
| 334 |
super().__init__(field, request, params, model, model_admin, field_path) |
| 335 |
if ( |
| 336 |
self.used_parameters |
| 337 |
and self.lookup_kwarg in self.used_parameters |
| 338 |
and self.used_parameters[self.lookup_kwarg] in ("1", "0") |
| 339 |
): |
| 340 |
self.used_parameters[self.lookup_kwarg] = bool( |
| 341 |
int(self.used_parameters[self.lookup_kwarg]) |
| 342 |
) |
| 343 |
|
| 344 |
def expected_parameters(self): |
| 345 |
return [self.lookup_kwarg, self.lookup_kwarg2] |
| 346 |
|
| 347 |
def get_facet_counts(self, pk_attname, filtered_qs): |
| 348 |
return { |
| 349 |
"true__c": models.Count( |
| 350 |
pk_attname, filter=models.Q(**{self.field_path: True}) |
| 351 |
), |
| 352 |
"false__c": models.Count( |
| 353 |
pk_attname, filter=models.Q(**{self.field_path: False}) |
| 354 |
), |
| 355 |
"null__c": models.Count( |
| 356 |
pk_attname, filter=models.Q(**{self.lookup_kwarg2: True}) |
| 357 |
), |
| 358 |
} |
| 359 |
|
| 360 |
def choices(self, changelist): |
| 361 |
field_choices = dict(self.field.flatchoices) |
| 362 |
add_facets = changelist.add_facets |
| 363 |
facet_counts = self.get_facet_queryset(changelist) if add_facets else None |
| 364 |
for lookup, title, count_field in ( |
| 365 |
(None, _("All"), None), |
| 366 |
("1", field_choices.get(True, _("Yes")), "true__c"), |
| 367 |
("0", field_choices.get(False, _("No")), "false__c"), |
| 368 |
): |
| 369 |
if add_facets: |
| 370 |
if count_field is not None: |
| 371 |
count = facet_counts[count_field] |
| 372 |
title = f"{title} ({count})" |
| 373 |
yield { |
| 374 |
"selected": self.lookup_val == lookup and not self.lookup_val2, |
| 375 |
"query_string": changelist.get_query_string( |
| 376 |
{self.lookup_kwarg: lookup}, [self.lookup_kwarg2] |
| 377 |
), |
| 378 |
"display": title, |
| 379 |
} |
| 380 |
if self.field.null: |
| 381 |
display = field_choices.get(None, _("Unknown")) |
| 382 |
if add_facets: |
| 383 |
count = facet_counts["null__c"] |
| 384 |
display = f"{display} ({count})" |
| 385 |
yield { |
| 386 |
"selected": self.lookup_val2 == "True", |
| 387 |
"query_string": changelist.get_query_string( |
| 388 |
{self.lookup_kwarg2: "True"}, [self.lookup_kwarg] |
| 389 |
), |
| 390 |
"display": display, |
| 391 |
} |
| 392 |
|
| 393 |
|
| 394 |
FieldListFilter.register( |
| 395 |
lambda f: isinstance(f, models.BooleanField), BooleanFieldListFilter |
| 396 |
) |
| 397 |
|
| 398 |
|
| 399 |
class ChoicesFieldListFilter(FieldListFilter): |
| 400 |
def __init__(self, field, request, params, model, model_admin, field_path): |
| 401 |
self.lookup_kwarg = "%s__exact" % field_path |
| 402 |
self.lookup_kwarg_isnull = "%s__isnull" % field_path |
| 403 |
self.lookup_val = params.get(self.lookup_kwarg) |
| 404 |
self.lookup_val_isnull = get_last_value_from_parameters( |
| 405 |
params, self.lookup_kwarg_isnull |
| 406 |
) |
| 407 |
super().__init__(field, request, params, model, model_admin, field_path) |
| 408 |
|
| 409 |
def expected_parameters(self): |
| 410 |
return [self.lookup_kwarg, self.lookup_kwarg_isnull] |
| 411 |
|
| 412 |
def get_facet_counts(self, pk_attname, filtered_qs): |
| 413 |
return { |
| 414 |
f"{i}__c": models.Count( |
| 415 |
pk_attname, |
| 416 |
filter=models.Q( |
| 417 |
(self.lookup_kwarg, value) |
| 418 |
if value is not None |
| 419 |
else (self.lookup_kwarg_isnull, True) |
| 420 |
), |
| 421 |
) |
| 422 |
for i, (value, _) in enumerate(self.field.flatchoices) |
| 423 |
} |
| 424 |
|
| 425 |
def choices(self, changelist): |
| 426 |
add_facets = changelist.add_facets |
| 427 |
facet_counts = self.get_facet_queryset(changelist) if add_facets else None |
| 428 |
yield { |
| 429 |
"selected": self.lookup_val is None, |
| 430 |
"query_string": changelist.get_query_string( |
| 431 |
remove=[self.lookup_kwarg, self.lookup_kwarg_isnull] |
| 432 |
), |
| 433 |
"display": _("All"), |
| 434 |
} |
| 435 |
none_title = "" |
| 436 |
for i, (lookup, title) in enumerate(self.field.flatchoices): |
| 437 |
if add_facets: |
| 438 |
count = facet_counts[f"{i}__c"] |
| 439 |
title = f"{title} ({count})" |
| 440 |
if lookup is None: |
| 441 |
none_title = title |
| 442 |
continue |
| 443 |
yield { |
| 444 |
"selected": self.lookup_val is not None |
| 445 |
and str(lookup) in self.lookup_val, |
| 446 |
"query_string": changelist.get_query_string( |
| 447 |
{self.lookup_kwarg: lookup}, [self.lookup_kwarg_isnull] |
| 448 |
), |
| 449 |
"display": title, |
| 450 |
} |
| 451 |
if none_title: |
| 452 |
yield { |
| 453 |
"selected": bool(self.lookup_val_isnull), |
| 454 |
"query_string": changelist.get_query_string( |
| 455 |
{self.lookup_kwarg_isnull: "True"}, [self.lookup_kwarg] |
| 456 |
), |
| 457 |
"display": none_title, |
| 458 |
} |
| 459 |
|
| 460 |
|
| 461 |
FieldListFilter.register(lambda f: bool(f.choices), ChoicesFieldListFilter) |
| 462 |
|
| 463 |
|
| 464 |
class DateFieldListFilter(FieldListFilter): |
| 465 |
def __init__(self, field, request, params, model, model_admin, field_path): |
| 466 |
self.field_generic = "%s__" % field_path |
| 467 |
self.date_params = { |
| 468 |
k: v[-1] for k, v in params.items() if k.startswith(self.field_generic) |
| 469 |
} |
| 470 |
|
| 471 |
now = timezone.now() |
| 472 |
# When time zone support is enabled, convert "now" to the user's time |
| 473 |
# zone so Django's definition of "Today" matches what the user expects. |
| 474 |
if timezone.is_aware(now): |
| 475 |
now = timezone.localtime(now) |
| 476 |
|
| 477 |
if isinstance(field, models.DateTimeField): |
| 478 |
today = now.replace(hour=0, minute=0, second=0, microsecond=0) |
| 479 |
else: # field is a models.DateField |
| 480 |
today = now.date() |
| 481 |
tomorrow = today + datetime.timedelta(days=1) |
| 482 |
if today.month == 12: |
| 483 |
next_month = today.replace(year=today.year + 1, month=1, day=1) |
| 484 |
else: |
| 485 |
next_month = today.replace(month=today.month + 1, day=1) |
| 486 |
next_year = today.replace(year=today.year + 1, month=1, day=1) |
| 487 |
|
| 488 |
self.lookup_kwarg_since = "%s__gte" % field_path |
| 489 |
self.lookup_kwarg_until = "%s__lt" % field_path |
| 490 |
self.links = ( |
| 491 |
(_("Any date"), {}), |
| 492 |
( |
| 493 |
_("Today"), |
| 494 |
{ |
| 495 |
self.lookup_kwarg_since: today, |
| 496 |
self.lookup_kwarg_until: tomorrow, |
| 497 |
}, |
| 498 |
), |
| 499 |
( |
| 500 |
_("Past 7 days"), |
| 501 |
{ |
| 502 |
self.lookup_kwarg_since: today - datetime.timedelta(days=7), |
| 503 |
self.lookup_kwarg_until: tomorrow, |
| 504 |
}, |
| 505 |
), |
| 506 |
( |
| 507 |
_("This month"), |
| 508 |
{ |
| 509 |
self.lookup_kwarg_since: today.replace(day=1), |
| 510 |
self.lookup_kwarg_until: next_month, |
| 511 |
}, |
| 512 |
), |
| 513 |
( |
| 514 |
_("This year"), |
| 515 |
{ |
| 516 |
self.lookup_kwarg_since: today.replace(month=1, day=1), |
| 517 |
self.lookup_kwarg_until: next_year, |
| 518 |
}, |
| 519 |
), |
| 520 |
) |
| 521 |
if field.null: |
| 522 |
self.lookup_kwarg_isnull = "%s__isnull" % field_path |
| 523 |
self.links += ( |
| 524 |
(_("No date"), {self.field_generic + "isnull": True}), |
| 525 |
(_("Has date"), {self.field_generic + "isnull": False}), |
| 526 |
) |
| 527 |
super().__init__(field, request, params, model, model_admin, field_path) |
| 528 |
|
| 529 |
def expected_parameters(self): |
| 530 |
params = [self.lookup_kwarg_since, self.lookup_kwarg_until] |
| 531 |
if self.field.null: |
| 532 |
params.append(self.lookup_kwarg_isnull) |
| 533 |
return params |
| 534 |
|
| 535 |
def get_facet_counts(self, pk_attname, filtered_qs): |
| 536 |
return { |
| 537 |
f"{i}__c": models.Count(pk_attname, filter=models.Q(**param_dict)) |
| 538 |
for i, (_, param_dict) in enumerate(self.links) |
| 539 |
} |
| 540 |
|
| 541 |
def choices(self, changelist): |
| 542 |
add_facets = changelist.add_facets |
| 543 |
facet_counts = self.get_facet_queryset(changelist) if add_facets else None |
| 544 |
for i, (title, param_dict) in enumerate(self.links): |
| 545 |
param_dict_str = {key: str(value) for key, value in param_dict.items()} |
| 546 |
if add_facets: |
| 547 |
count = facet_counts[f"{i}__c"] |
| 548 |
title = f"{title} ({count})" |
| 549 |
yield { |
| 550 |
"selected": self.date_params == param_dict_str, |
| 551 |
"query_string": changelist.get_query_string( |
| 552 |
param_dict_str, [self.field_generic] |
| 553 |
), |
| 554 |
"display": title, |
| 555 |
} |
| 556 |
|
| 557 |
|
| 558 |
FieldListFilter.register(lambda f: isinstance(f, models.DateField), DateFieldListFilter) |
| 559 |
|
| 560 |
|
| 561 |
# This should be registered last, because it's a last resort. For example, |
| 562 |
# if a field is eligible to use the BooleanFieldListFilter, that'd be much |
| 563 |
# more appropriate, and the AllValuesFieldListFilter won't get used for it. |
| 564 |
class AllValuesFieldListFilter(FieldListFilter): |
| 565 |
def __init__(self, field, request, params, model, model_admin, field_path): |
| 566 |
self.lookup_kwarg = field_path |
| 567 |
self.lookup_kwarg_isnull = "%s__isnull" % field_path |
| 568 |
self.lookup_val = params.get(self.lookup_kwarg) |
| 569 |
self.lookup_val_isnull = get_last_value_from_parameters( |
| 570 |
params, self.lookup_kwarg_isnull |
| 571 |
) |
| 572 |
self.empty_value_display = model_admin.get_empty_value_display() |
| 573 |
parent_model, reverse_path = reverse_field_path(model, field_path) |
| 574 |
# Obey parent ModelAdmin queryset when deciding which options to show |
| 575 |
if model == parent_model: |
| 576 |
queryset = model_admin.get_queryset(request) |
| 577 |
else: |
| 578 |
queryset = parent_model._default_manager.all() |
| 579 |
self.lookup_choices = ( |
| 580 |
queryset.distinct().order_by(field.name).values_list(field.name, flat=True) |
| 581 |
) |
| 582 |
super().__init__(field, request, params, model, model_admin, field_path) |
| 583 |
|
| 584 |
def expected_parameters(self): |
| 585 |
return [self.lookup_kwarg, self.lookup_kwarg_isnull] |
| 586 |
|
| 587 |
def get_facet_counts(self, pk_attname, filtered_qs): |
| 588 |
return { |
| 589 |
f"{i}__c": models.Count( |
| 590 |
pk_attname, |
| 591 |
filter=models.Q( |
| 592 |
(self.lookup_kwarg, value) |
| 593 |
if value is not None |
| 594 |
else (self.lookup_kwarg_isnull, True) |
| 595 |
), |
| 596 |
) |
| 597 |
for i, value in enumerate(self.lookup_choices) |
| 598 |
} |
| 599 |
|
| 600 |
def choices(self, changelist): |
| 601 |
add_facets = changelist.add_facets |
| 602 |
facet_counts = self.get_facet_queryset(changelist) if add_facets else None |
| 603 |
yield { |
| 604 |
"selected": self.lookup_val is None and self.lookup_val_isnull is None, |
| 605 |
"query_string": changelist.get_query_string( |
| 606 |
remove=[self.lookup_kwarg, self.lookup_kwarg_isnull] |
| 607 |
), |
| 608 |
"display": _("All"), |
| 609 |
} |
| 610 |
include_none = False |
| 611 |
count = None |
| 612 |
empty_title = self.empty_value_display |
| 613 |
for i, val in enumerate(self.lookup_choices): |
| 614 |
if add_facets: |
| 615 |
count = facet_counts[f"{i}__c"] |
| 616 |
if val is None: |
| 617 |
include_none = True |
| 618 |
empty_title = f"{empty_title} ({count})" if add_facets else empty_title |
| 619 |
continue |
| 620 |
val = str(val) |
| 621 |
yield { |
| 622 |
"selected": self.lookup_val is not None and val in self.lookup_val, |
| 623 |
"query_string": changelist.get_query_string( |
| 624 |
{self.lookup_kwarg: val}, [self.lookup_kwarg_isnull] |
| 625 |
), |
| 626 |
"display": f"{val} ({count})" if add_facets else val, |
| 627 |
} |
| 628 |
if include_none: |
| 629 |
yield { |
| 630 |
"selected": bool(self.lookup_val_isnull), |
| 631 |
"query_string": changelist.get_query_string( |
| 632 |
{self.lookup_kwarg_isnull: "True"}, [self.lookup_kwarg] |
| 633 |
), |
| 634 |
"display": empty_title, |
| 635 |
} |
| 636 |
|
| 637 |
|
| 638 |
FieldListFilter.register(lambda f: True, AllValuesFieldListFilter) |
| 639 |
|
| 640 |
|
| 641 |
class RelatedOnlyFieldListFilter(RelatedFieldListFilter): |
| 642 |
def field_choices(self, field, request, model_admin): |
| 643 |
pk_qs = ( |
| 644 |
model_admin.get_queryset(request) |
| 645 |
.distinct() |
| 646 |
.values_list("%s__pk" % self.field_path, flat=True) |
| 647 |
) |
| 648 |
ordering = self.field_admin_ordering(field, request, model_admin) |
| 649 |
return field.get_choices( |
| 650 |
include_blank=False, limit_choices_to={"pk__in": pk_qs}, ordering=ordering |
| 651 |
) |
| 652 |
|
| 653 |
|
| 654 |
class EmptyFieldListFilter(FieldListFilter): |
| 655 |
def __init__(self, field, request, params, model, model_admin, field_path): |
| 656 |
if not field.empty_strings_allowed and not field.null: |
| 657 |
raise ImproperlyConfigured( |
| 658 |
"The list filter '%s' cannot be used with field '%s' which " |
| 659 |
"doesn't allow empty strings and nulls." |
| 660 |
% ( |
| 661 |
self.__class__.__name__, |
| 662 |
field.name, |
| 663 |
) |
| 664 |
) |
| 665 |
self.lookup_kwarg = "%s__isempty" % field_path |
| 666 |
self.lookup_val = get_last_value_from_parameters(params, self.lookup_kwarg) |
| 667 |
super().__init__(field, request, params, model, model_admin, field_path) |
| 668 |
|
| 669 |
def get_lookup_condition(self): |
| 670 |
lookup_conditions = [] |
| 671 |
if self.field.empty_strings_allowed: |
| 672 |
lookup_conditions.append((self.field_path, "")) |
| 673 |
if self.field.null: |
| 674 |
lookup_conditions.append((f"{self.field_path}__isnull", True)) |
| 675 |
return models.Q.create(lookup_conditions, connector=models.Q.OR) |
| 676 |
|
| 677 |
def queryset(self, request, queryset): |
| 678 |
if self.lookup_kwarg not in self.used_parameters: |
| 679 |
return queryset |
| 680 |
if self.lookup_val not in ("0", "1"): |
| 681 |
raise IncorrectLookupParameters |
| 682 |
|
| 683 |
lookup_condition = self.get_lookup_condition() |
| 684 |
if self.lookup_val == "1": |
| 685 |
return queryset.filter(lookup_condition) |
| 686 |
return queryset.exclude(lookup_condition) |
| 687 |
|
| 688 |
def expected_parameters(self): |
| 689 |
return [self.lookup_kwarg] |
| 690 |
|
| 691 |
def get_facet_counts(self, pk_attname, filtered_qs): |
| 692 |
lookup_condition = self.get_lookup_condition() |
| 693 |
return { |
| 694 |
"empty__c": models.Count(pk_attname, filter=lookup_condition), |
| 695 |
"not_empty__c": models.Count(pk_attname, filter=~lookup_condition), |
| 696 |
} |
| 697 |
|
| 698 |
def choices(self, changelist): |
| 699 |
add_facets = changelist.add_facets |
| 700 |
facet_counts = self.get_facet_queryset(changelist) if add_facets else None |
| 701 |
for lookup, title, count_field in ( |
| 702 |
(None, _("All"), None), |
| 703 |
("1", _("Empty"), "empty__c"), |
| 704 |
("0", _("Not empty"), "not_empty__c"), |
| 705 |
): |
| 706 |
if add_facets: |
| 707 |
if count_field is not None: |
| 708 |
count = facet_counts[count_field] |
| 709 |
title = f"{title} ({count})" |
| 710 |
yield { |
| 711 |
"selected": self.lookup_val == lookup, |
| 712 |
"query_string": changelist.get_query_string( |
| 713 |
{self.lookup_kwarg: lookup} |
| 714 |
), |
| 715 |
"display": title, |
| 716 |
} |