Skip to content

Commit 87bb901

Browse files
committed
chg: handle __in=[] gracefully on Solr
This commit avoids the need to check whether a list is empty to avoid an error when using it for an `__in` filter. Closes django-haystack#358 Closes django-haystack#1311
1 parent e6a5cdd commit 87bb901

File tree

3 files changed

+26
-3
lines changed

3 files changed

+26
-3
lines changed

haystack/backends/solr_backend.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -581,10 +581,13 @@ def build_query_fragment(self, field, filter_type, value):
581581
elif filter_type == 'in':
582582
in_options = []
583583

584-
for possible_value in prepared_value:
585-
in_options.append(u'"%s"' % self.backend.conn._from_python(possible_value))
584+
if not prepared_value:
585+
query_frag = u'(!*:*)'
586+
else:
587+
for possible_value in prepared_value:
588+
in_options.append(u'"%s"' % self.backend.conn._from_python(possible_value))
586589

587-
query_frag = u"(%s)" % " OR ".join(in_options)
590+
query_frag = u"(%s)" % " OR ".join(in_options)
588591
elif filter_type == 'range':
589592
start = self.backend.conn._from_python(prepared_value[0])
590593
end = self.backend.conn._from_python(prepared_value[1])

test_haystack/solr_tests/test_solr_backend.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -962,6 +962,17 @@ def test_auto_query(self):
962962
sqs = sqs.filter(tags__in=['cameras', 'electronics'])
963963
self.assertEqual(len(sqs), 0)
964964

965+
def test_query__in(self):
966+
self.assertGreater(len(self.sqs), 0)
967+
sqs = self.sqs.filter(django_ct='core.mockmodel', django_id__in=[1,2])
968+
self.assertEqual(len(sqs), 2)
969+
970+
def test_query__in_empty_list(self):
971+
"""Confirm that an empty list avoids a Solr exception"""
972+
self.assertGreater(len(self.sqs), 0)
973+
sqs = self.sqs.filter(id__in=[])
974+
self.assertEqual(len(sqs), 0)
975+
965976
# Regressions
966977

967978
def test_regression_proper_start_offsets(self):

test_haystack/solr_tests/test_solr_query.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,3 +179,12 @@ def test_narrow_sq(self):
179179
self.assertTrue(isinstance(sqs, SearchQuerySet))
180180
self.assertEqual(len(sqs.query.narrow_queries), 1)
181181
self.assertEqual(sqs.query.narrow_queries.pop(), 'foo:(moof)')
182+
183+
def test_query__in(self):
184+
sqs = SearchQuerySet(using='solr').filter(id__in=[1,2,3])
185+
self.assertEqual(sqs.query.build_query(), u'id:("1" OR "2" OR "3")')
186+
187+
def test_query__in_empty_list(self):
188+
"""Confirm that an empty list avoids a Solr exception"""
189+
sqs = SearchQuerySet(using='solr').filter(id__in=[])
190+
self.assertEqual(sqs.query.build_query(), u'id:(!*:*)')

0 commit comments

Comments
 (0)