Skip to content

Commit

Permalink
Closes netbox-community#552: Added a None filter option for custom se…
Browse files Browse the repository at this point in the history
…lect fields
  • Loading branch information
jeremystretch committed Sep 16, 2016
1 parent 386a8a2 commit c882525
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 9 deletions.
17 changes: 15 additions & 2 deletions netbox/extras/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,30 @@

from django.contrib.contenttypes.models import ContentType

from .models import CustomField
from .models import CF_TYPE_SELECT, 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 __init__(self, cf_type, *args, **kwargs):
self.cf_type = cf_type
super(CustomFieldFilter, self).__init__(*args, **kwargs)

def filter(self, queryset, value):
# Skip filter on empty value
if not value.strip():
return queryset
# Treat 0 as None for Select fields
try:
if self.cf_type == CF_TYPE_SELECT and int(value) == 0:
return queryset.exclude(
custom_field_values__field__name=self.name,
)
except ValueError:
pass
return queryset.filter(
custom_field_values__field__name=self.name,
custom_field_values__serialized_value=value,
Expand All @@ -30,4 +43,4 @@ def __init__(self, *args, **kwargs):
obj_type = ContentType.objects.get_for_model(self._meta.model)
custom_fields = CustomField.objects.filter(obj_type=obj_type, is_filterable=True)
for cf in custom_fields:
self.filters['cf_{}'.format(cf.name)] = CustomFieldFilter(name=cf.name)
self.filters['cf_{}'.format(cf.name)] = CustomFieldFilter(name=cf.name, cf_type=cf.type)
12 changes: 5 additions & 7 deletions netbox/extras/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,12 @@ def get_custom_fields_for_model(content_type, filterable_only=False, bulk_edit=F

# Select
elif cf.type == CF_TYPE_SELECT:
if bulk_edit:
choices = [(cfc.pk, cfc) for cfc in cf.choices.all()]
if not cf.required:
choices = [(0, 'None')] + choices
choices = [(cfc.pk, cfc) for cfc in cf.choices.all()]
if not cf.required:
choices = [(0, 'None')] + choices
if bulk_edit or filterable_only:
choices = [(None, '---------')] + choices
field = forms.TypedChoiceField(choices=choices, coerce=int, required=cf.required)
else:
field = forms.ModelChoiceField(queryset=cf.choices.all(), required=cf.required)
field = forms.TypedChoiceField(choices=choices, coerce=int, required=cf.required)

# URL
elif cf.type == CF_TYPE_URL:
Expand Down

0 comments on commit c882525

Please sign in to comment.