From 10ac56c5e984a5f01a1742c1826d38d6c8bf323b Mon Sep 17 00:00:00 2001 From: Sam Date: Mon, 15 Feb 2021 11:59:24 +0000 Subject: [PATCH] improvemnets to filters provided by product search results --- products/tests.py | 4 ++-- products/utils.py | 53 ++++++++++++++++++++++++++++++++++++++++++----- 2 files changed, 50 insertions(+), 7 deletions(-) diff --git a/products/tests.py b/products/tests.py index a21ac34..bfd73d5 100644 --- a/products/tests.py +++ b/products/tests.py @@ -471,8 +471,6 @@ class ProductSearchTest(TestCase): self.factory(tags="azules"), ] - self.factory(tags="azul") - query_string = quote("zapatos rojos") url = f"{self.endpoint}?query_string={query_string}" @@ -483,6 +481,8 @@ class ProductSearchTest(TestCase): self.assertEqual(response.status_code, 200) # check for object creation self.assertEquals(len(payload['products']), len(expected_instances)) + # check for filters + self.assertNotEquals([], payload['filters']['singles']) class MyProductsViewTest(APITestCase): diff --git a/products/utils.py b/products/utils.py index 3f5eeb1..13b04aa 100644 --- a/products/utils.py +++ b/products/utils.py @@ -1,9 +1,52 @@ +import logging + def extract_search_filters(result_set): - filters = set() + """ + Returned object should look something like: + { + "singles": [], # non tree tags + "entry_1": [ 'tag1', 'tag2' ], + "entry_2": [ 'tag1', 'tag2' ], + } + """ + filter_dict = { + 'singles': set(), + } for item in result_set: - tags = item.tags.all() - for tag in tags: - filters.add(tag.name) - return list(filters) + # import ipdb; ipdb.set_trace() + try: + # extract tags + tags = item.tags.all() + for tag in tags: + if len(tag.name.split('/')) == 1: + filter_dict['singles'].add(tag.name) + else: + # set penultimate tag as header + chunks = tag.name.split('/') + header = chunks[-2] + name = chunks[-1] + # check if + entry = filter_dict.get(header) + if entry is None: + filter_dict[header] = set() + filter_dict[header].add(name) + # extract attributes + attributes = item.attributes.all() + for tag in attributes: + if len(tag.name.split('/')) == 1: + filter_dict['singles'].add(tag.name) + else: + # set penultimate tag as header + chunks = tag.name.split('/') + header = chunks[-2] + name = chunks[-1] + # check if + entry = filter_dict.get(header) + if entry is None: + filter_dict[header] = set() + filter_dict[header].add(name) + except Exception as e: + logging.error(f'Extacting filters for {item}') + return filter_dict