Skip to content

Commit

Permalink
- Single class field filter
Browse files Browse the repository at this point in the history
  • Loading branch information
elipe17 committed Aug 26, 2024
1 parent 0e50553 commit 0952cc0
Showing 1 changed file with 17 additions and 22 deletions.
39 changes: 17 additions & 22 deletions django508/tests/admin/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,29 +7,8 @@
from django.core.exceptions import ValidationError
from django.contrib.admin.options import IncorrectLookupParameters

class MultiSelectMixin:
"""Mixin for multi-select filters."""

def queryset(self, request, queryset):
"""Build queryset based on choices."""
params = Q()
for lookup_arg, value in self.used_parameters.items():
params |= Q(**{lookup_arg: value})
try:
return queryset.filter(params)
except (ValueError, ValidationError) as e:
# Fields may raise a ValueError or ValidationError when converting
# the parameters to the correct type.
raise IncorrectLookupParameters(e)

def prepare_querystring_value(self, value):
"""Preparse the query string value."""
# mask all commas or these values will be used
# in a comma-seperated-list as get-parameter
return str(value).replace(',', '%~')


class FieldListMultiSelectFilter(MultiSelectMixin, admin.AllValuesFieldListFilter):
class FieldListMultiSelectFilter(admin.AllValuesFieldListFilter):
"""Multi select dropdown filter for all kind of fields."""

template = 'multiselectdropdownfilter.html'
Expand All @@ -53,6 +32,22 @@ def __init__(self, field, request, params, model, model_admin, field_path):
.values_list(field.name, flat=True))
super(admin.AllValuesFieldListFilter, self).__init__(field, request, params, model, model_admin, field_path)

def queryset(self, request, queryset):
"""Build queryset based on choices."""
params = Q()
for lookup_arg, value in self.used_parameters.items():
params |= Q(**{lookup_arg: value})
try:
return queryset.filter(params)
except (ValueError, ValidationError) as e:
# Fields may raise a ValueError or ValidationError when converting
# the parameters to the correct type.
raise IncorrectLookupParameters(e)

def prepare_querystring_value(self, value):
"""Mask commas."""
return str(value).replace(',', '%~')

def choices(self, changelist):
"""Generate choices."""
add_facets = getattr(changelist, "add_facets", False)
Expand Down

0 comments on commit 0952cc0

Please sign in to comment.