From 127a0b47b7361b72b4cf32cccfe9f9088d7ffd71 Mon Sep 17 00:00:00 2001
From: Martin Burchell <martinb@aptivate.org>
Date: Tue, 11 Dec 2018 16:00:13 +0000
Subject: [PATCH] Ignore empty term filter

This was causing zero results to be returned if only the taxonomy was specified
and not the term
---
 .../rest_api/tests/item_list_view_tests.py      | 17 +++++++++++++++++
 internewshid/rest_api/views.py                  | 15 ++++++++-------
 2 files changed, 25 insertions(+), 7 deletions(-)

diff --git a/internewshid/rest_api/tests/item_list_view_tests.py b/internewshid/rest_api/tests/item_list_view_tests.py
index 6d678b88..a1e2122a 100644
--- a/internewshid/rest_api/tests/item_list_view_tests.py
+++ b/internewshid/rest_api/tests/item_list_view_tests.py
@@ -159,6 +159,23 @@ def test_filter_by_term_works_when_term_name_includes_colon():
     assert payload[0]['body'] == item['body']
 
 
+@pytest.mark.django_db
+def test_empty_term_filter_ignored():
+    taxonomy = create_taxonomy(name='taxonomy').data
+    term = add_term(taxonomy=taxonomy['slug'], name='my term').data
+    item1 = create_item(body='item 1').data
+    item2 = create_item(body='item 2').data
+    categorize_item(item1, term)
+
+    term_filter = '{}:'.format(taxonomy['slug'])
+    payload = get(data={'terms': [term_filter]}).data
+
+    assert len(payload) == 2
+    assert payload[0]['body'] == item1['body']
+    assert payload[1]['body'] == item2['body']
+
+
+
 @pytest.mark.django_db
 def test_item_listed_with_associated_terms():
     # TODO: Refactor to use the REST API when we can add
diff --git a/internewshid/rest_api/views.py b/internewshid/rest_api/views.py
index 8b82c32f..d8fbd7a1 100644
--- a/internewshid/rest_api/views.py
+++ b/internewshid/rest_api/views.py
@@ -63,14 +63,15 @@ class ItemViewSet(viewsets.ModelViewSet, BulkDestroyModelMixin):
         terms = self.request.query_params.getlist('terms', [])
         for taxonomy_and_term in terms:
             (taxonomy, term) = taxonomy_and_term.split(':', 1)
-            matches = Term.objects.filter(
-                name=term, taxonomy__slug=taxonomy
-            )
-            if len(matches) == 0:
-                # If the term doesn't exist, there can be no matches
-                return Item.objects.none()
+            if term:
+                matches = Term.objects.filter(
+                    name=term, taxonomy__slug=taxonomy
+                )
+                if len(matches) == 0:
+                    # If the term doesn't exist, there can be no matches
+                    return Item.objects.none()
 
-            items = items.filter(terms__id=matches[0].id)
+                items = items.filter(terms__id=matches[0].id)
 
         location = self.request.query_params.get('location', None)
         if location is not None:
-- 
GitLab