Skip to content

Commit

Permalink
Fixes #11539: Use BooleanFilter for 'empty' lookups (#11784)
Browse files Browse the repository at this point in the history
* Use BooleanFilter for 'empty' lookups

* Always use BooleanFilter for 'empty' lookups

* Restore Empty lookup logic
  • Loading branch information
jeremystretch authored May 25, 2023
1 parent bf1c191 commit 24a51dd
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 7 deletions.
14 changes: 8 additions & 6 deletions netbox/extras/lookups.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@ class Empty(Lookup):
Filter on whether a string is empty.
"""
lookup_name = 'empty'

def as_sql(self, qn, connection):
lhs, lhs_params = self.process_lhs(qn, connection)
rhs, rhs_params = self.process_rhs(qn, connection)
params = lhs_params + rhs_params
return 'CAST(LENGTH(%s) AS BOOLEAN) != %s' % (lhs, rhs), params
prepare_rhs = False

def as_sql(self, compiler, connection):
sql, params = compiler.compile(self.lhs)
if self.rhs:
return f"CAST(LENGTH({sql}) AS BOOLEAN) IS NOT TRUE", params
else:
return f"CAST(LENGTH({sql}) AS BOOLEAN) IS TRUE", params


class NetContainsOrEquals(Lookup):
Expand Down
11 changes: 10 additions & 1 deletion netbox/netbox/filtersets.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,8 @@ def get_additional_lookups(cls, existing_filter_name, existing_filter):
# create the new filter with the same type because there is no guarantee the defined type
# is the same as the default type for the field
resolve_field(field, lookup_expr) # Will raise FieldLookupError if the lookup is invalid
new_filter = type(existing_filter)(
filter_cls = django_filters.BooleanFilter if lookup_expr == 'empty' else type(existing_filter)
new_filter = filter_cls(
field_name=field_name,
lookup_expr=lookup_expr,
label=existing_filter.label,
Expand Down Expand Up @@ -224,6 +225,14 @@ def get_filters(cls):

return filters

@classmethod
def filter_for_lookup(cls, field, lookup_type):

if lookup_type == 'empty':
return django_filters.BooleanFilter, {}

return super().filter_for_lookup(field, lookup_type)


class ChangeLoggedModelFilterSet(BaseFilterSet):
"""
Expand Down

0 comments on commit 24a51dd

Please sign in to comment.