An easy way to exclude #1484
Unanswered
smartlegionlab
asked this question in
Q&A
Replies: 2 comments
-
I really want this too, #978 and see this discussion about it, #1484 |
Beta Was this translation helpful? Give feedback.
0 replies
-
As per @carltongibson mentioned here it's possible with some extensions and overwriting. FilterSet code from django_filters import FilterSet
from django_filters.conf import settings
from django_filters.filterset import resolve_field
class AutomaticallyExcludeFilterSet(FilterSet):
@classmethod
def get_filter_name(cls, field_name, lookup_expr):
if lookup_expr[0] == "!":
lookup_expr = lookup_expr[1:]
suffix = "!"
else:
suffix = ""
field_name = super().get_filter_name(field_name, lookup_expr)
return f"{field_name}{suffix}"
@classmethod
def filter_for_field(cls, field, field_name, lookup_expr=None):
if lookup_expr is None:
lookup_expr = settings.DEFAULT_LOOKUP_EXPR
if lookup_expr[0] == "!":
lookup_expr = lookup_expr[1:]
exclude = True
else:
exclude = False
field, lookup_type = resolve_field(field, lookup_expr)
default = {
"field_name": field_name,
"lookup_expr": lookup_expr,
"exclude": exclude,
}
filter_class, params = cls.filter_for_lookup(field, lookup_type)
default.update(params)
assert filter_class is not None, (
"%s resolved field '%s' with '%s' lookup to an unrecognized field "
"type %s. Try adding an override to 'Meta.filter_overrides'. See: "
"https://django-filter.readthedocs.io/en/main/ref/filterset.html"
"#customise-filter-generation-with-filter-overrides"
) % (cls.__name__, field_name, lookup_expr, field.__class__.__name__)
return filter_class(**default) backend code from django_filters.rest_framework.backends import DjangoFilterBackend
class AutomaticallyExcludeDjangoFilterBackend(DjangoFilterBackend):
filterset_base = AutomaticallyExcludeFilterSet |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hello, is there any easy way to exclude?
For example, there is a filter in which there are a lot of city names.
For filtering, I can choose the ones I need, but what if I need all but one? All that comes to mind is to add a second similar filter below with exclude=True, but what if I have very large forms, duplicating filters to add the possibility of exclusion is clearly not an option?
This approach is clearly redundant and wrong. But I couldn't find anything in the official documentation:
The second thing that comes to mind is to use some kind of "Select All" method. In order to remove unnecessary options after choosing with one team.
Beta Was this translation helpful? Give feedback.
All reactions