1
0
mirror of https://github.com/netbox-community/netbox.git synced 2024-05-10 07:54:54 +00:00

Implemented dynamic filters for custom fields

This commit is contained in:
Jeremy Stretch
2016-08-23 11:18:00 -04:00
parent 3b36a35b9a
commit 28b9dda55d
5 changed files with 47 additions and 12 deletions

31
netbox/extras/filters.py Normal file
View File

@@ -0,0 +1,31 @@
import django_filters
from django.contrib.contenttypes.models import ContentType
from .models import CustomField
class CustomFieldFilter(django_filters.Filter):
"""
Filter objects by the presence of a CustomFieldValue. The filter's name is used as the CustomField name.
"""
def filter(self, queryset, value):
return queryset.filter(
custom_field_values__field__name=self.name,
custom_field_values__serialized_value=value,
)
class CustomFieldFilterSet(django_filters.FilterSet):
"""
Dynamically add a Filter for each CustomField applicable to the parent model.
"""
def __init__(self, *args, **kwargs):
super(CustomFieldFilterSet, self).__init__(*args, **kwargs)
obj_type = ContentType.objects.get_for_model(self._meta.model)
custom_fields = CustomField.objects.filter(obj_type=obj_type)
for cf in custom_fields:
self.filters['cf_{}'.format(cf.name)] = CustomFieldFilter(name=cf.name)