Call filter from BoolOperand and catch LookupError

This commit is contained in:
Wayne Witzel III 2017-05-19 16:49:25 -04:00
parent b99a118aae
commit 530df327ca
2 changed files with 9 additions and 6 deletions

View File

@ -116,14 +116,14 @@ class TestSmartFilterQueryFromString():
@pytest.mark.parametrize("filter_string,q_expected", [
('search=foo', Q(**{u"name": u"foo"}) | Q(**{ u"description": u"foo"})),
('group__search=foo', Q(**{u"group__name": u"foo"}) | Q(**{u"group__description": u"foo"})),
('search=foo', Q(Q(**{u"name": u"foo"}) | Q(**{ u"description": u"foo"}))),
('group__search=foo', Q(Q(**{u"group__name": u"foo"}) | Q(**{u"group__description": u"foo"}))),
('search=foo and group__search=foo', Q(
Q(**{u"name": u"foo"}) | Q(**{ u"description": u"foo"}),
Q(**{u"group__name": u"foo"}) | Q(**{u"group__description": u"foo"}))),
('search=foo or ansible_facts__a=null',
(Q(**{u"name": u"foo"}) | Q(**{u"description": u"foo"})) |
Q(**{u"ansible_facts__contains": {u"a": u"null"}})),
Q(Q(**{u"name": u"foo"}) | Q(**{u"description": u"foo"})) |
Q(**{u"ansible_facts__contains": {u"a": u"null"}})),
])
def test_search_related_fields(self, mock_get_host_model, filter_string, q_expected):
q = SmartFilter.query_from_string(filter_string)

View File

@ -52,7 +52,7 @@ class SmartFilter(object):
if search_kwargs:
kwargs.update(search_kwargs)
q = reduce(lambda x, y: x | y, [django.db.models.Q(**{u'%s' % _k:_v}) for _k, _v in kwargs.items()])
self.result = q
self.result = Host.objects.filter(q)
else:
kwargs[k] = v
self.result = Host.objects.filter(**kwargs)
@ -162,7 +162,10 @@ class SmartFilter(object):
model = get_model('host')
elif k.endswith('__search'):
relation = k.split('__')[0]
model = get_model(relation)
try:
model = get_model(relation)
except LookupError:
raise ParseException('No related field named %s' % relation)
search_kwargs = {}
if model is not None: