Skip to content

Commit

Permalink
custom filters for IDs and labels of nodes (no matter if source or ta…
Browse files Browse the repository at this point in the history
…rget)
  • Loading branch information
csae8092 committed Nov 25, 2024
1 parent 278fe2d commit 55e6662
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 6 deletions.
52 changes: 46 additions & 6 deletions network/filters.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,63 @@
import django_filters
from django.db.models import CharField
from django.core.exceptions import FieldDoesNotExist
from django.db.models import CharField, Q
import django_filters.widgets

from network.models import Edge


def safe_int_conversion(value):
try:
return int(value)
except ValueError:
pass


class EdgeListFilter(django_filters.FilterSet):

node = django_filters.CharFilter(
field_name="source_label",
method="nodes_icontains_filter",
label="Quell- oder Zielknoten",
help_text="Sucht im Label des Ziel, oder des Quellknotens",
)
node_id = django_filters.BaseInFilter(
field_name="source_id",
method="nodes_id_filter",
label="IDs eines oder mehrerer Quell- oder Zielknoten",
help_text="IDs eines oder mehrerer Quell- oder Zielknoten, z.B. '2121,10815'",
widget=django_filters.widgets.CSVWidget(),
)
edge_label = django_filters.AllValuesMultipleFilter()

class Meta:
model = Edge
fields = "__all__"

def nodes_icontains_filter(self, queryset, name, value):
return queryset.filter(
Q(source_label__icontains=value) | Q(target_label__icontains=value)
)

def nodes_id_filter(self, queryset, name, value):
sane_values = [safe_int_conversion(x) for x in value]
print(value)
print(sane_values)
return queryset.filter(
Q(source_id__in=sane_values) | Q(target_id__in=sane_values)
)

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field_name, filter_obj in self.filters.items():
model_field = self.Meta.model._meta.get_field(field_name)
self.filters[field_name].label = model_field.verbose_name
self.filters[field_name].help_text = model_field.help_text

if isinstance(model_field, CharField):
try:
model_field = self.Meta.model._meta.get_field(field_name)
self.filters[field_name].label = model_field.verbose_name
self.filters[field_name].help_text = model_field.help_text
except FieldDoesNotExist:
continue
print(field_name, type(model_field))
if isinstance(model_field, CharField) and not field_name == "edge_label":
if (
model_field.choices
): # Keep the default filter logic for choice fields
Expand Down
2 changes: 2 additions & 0 deletions network/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ def __init__(self, *args, **kwargs):
self.form_method = "GET"
self.form_tag = False
self.layout = Layout(
"node",
"node_id",
BS5Accordion(
AccordionGroup(
"Quellknoten",
Expand Down

0 comments on commit 55e6662

Please sign in to comment.