Add special "contains any of" verb for string-based grid filters

This commit is contained in:
Lance Edgar 2021-02-12 13:57:54 -06:00
parent 1420a33649
commit 89f0336af9
4 changed files with 73 additions and 3 deletions

View file

@ -144,6 +144,7 @@ class GridFilter(object):
'is_empty_or_null': "is either empty or null",
'contains': "contains",
'does_not_contain': "does not contain",
'contains_any_of': "contains any of",
'is_me': "is me",
'is_not_me': "is not me",
}
@ -162,6 +163,10 @@ class GridFilter(object):
'is_not_me',
]
multiple_value_verbs = [
'contains_any_of',
]
value_renderer_factory = DefaultValueRenderer
data_type = 'string' # default, but will be set from value renderer
choices = {}
@ -382,6 +387,7 @@ class AlchemyStringFilter(AlchemyGridFilter):
Expose contains / does-not-contain verbs in addition to core.
"""
return ['contains', 'does_not_contain',
'contains_any_of',
'equal', 'not_equal',
'is_empty', 'is_not_empty',
'is_null', 'is_not_null',
@ -414,6 +420,39 @@ class AlchemyStringFilter(AlchemyGridFilter):
for v in value.split()]),
))
def filter_contains_any_of(self, query, value):
"""
This filter expects "multiple values" separated by newline character,
and will add an "OR" condition with each value being checked via
"ILIKE". For instance if the user submits a "value" like this:
.. code-block:: none
foo bar
baz
This will result in SQL condition like this:
.. code-block:: sql
(name ILIKE '%foo%' AND name ILIKE '%bar%') OR name ILIKE '%baz%'
"""
if not value:
return query
values = value.split('\n')
values = [value for value in values if value]
if not values:
return query
conditions = []
for value in values:
conditions.append(sa.and_(
*[self.column.ilike(self.encode_value('%{}%'.format(v)))
for v in value.split()]))
return query.filter(sa.or_(*conditions))
def filter_is_empty(self, query, value):
return query.filter(sa.func.trim(self.column) == self.encode_value(''))