Skip to content

Commit af857f5

Browse files
authored
Quick Search functionality (#226)
1 parent a91f96c commit af857f5

File tree

1 file changed

+20
-3
lines changed

1 file changed

+20
-3
lines changed

netbox_custom_objects/filtersets.py

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
import django_filters
22
from django.contrib.postgres.fields import ArrayField
3-
from django.db.models import JSONField
4-
from netbox.filtersets import BaseFilterSet, NetBoxModelFilterSet
3+
from django.db.models import JSONField, Q
4+
5+
from extras.choices import CustomFieldTypeChoices
6+
from netbox.filtersets import NetBoxModelFilterSet
57

68
from .models import CustomObjectType
79

@@ -51,13 +53,28 @@ def get_filterset_class(model):
5153
},
5254
)
5355

56+
def search(self, queryset, name, value):
57+
if not value.strip():
58+
return queryset
59+
q = Q()
60+
for field in model.custom_object_type.fields.all():
61+
if field.type in [
62+
CustomFieldTypeChoices.TYPE_TEXT,
63+
CustomFieldTypeChoices.TYPE_LONGTEXT,
64+
CustomFieldTypeChoices.TYPE_JSON,
65+
CustomFieldTypeChoices.TYPE_URL,
66+
]:
67+
q |= Q(**{f"{field.name}__icontains": value})
68+
return queryset.filter(q)
69+
5470
attrs = {
5571
"Meta": meta,
5672
"__module__": "database.filtersets",
73+
"search": search,
5774
}
5875

5976
return type(
6077
f"{model._meta.object_name}FilterSet",
61-
(BaseFilterSet,), # TODO: Should be a NetBoxModelFilterSet
78+
(NetBoxModelFilterSet,),
6279
attrs,
6380
)

0 commit comments

Comments
 (0)