From ef23ab1abc075be8149ff9f2884a565e582c76ff Mon Sep 17 00:00:00 2001 From: Oliver Walters Date: Thu, 18 Feb 2021 17:59:04 +1100 Subject: [PATCH] Adds functionality for traversing "through" installed items to extract test results --- InvenTree/stock/models.py | 47 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/InvenTree/stock/models.py b/InvenTree/stock/models.py index 84cc696593..5d7cce5132 100644 --- a/InvenTree/stock/models.py +++ b/InvenTree/stock/models.py @@ -699,6 +699,36 @@ class StockItem(MPTTModel): return True + def get_installed_items(self, cascade=False): + """ + Return all stock items which are *installed* in this one! + + Args: + cascade - Include items which are installed in items which are installed in items + + Note: This function is recursive, and may result in a number of database hits! + """ + + installed = set() + + items = StockItem.objects.filter(belongs_to=self) + + for item in items: + + # Prevent recursion + if item not in installed: + installed.add(item) + + if cascade: + sub_items = item.get_installed_items(cascade=True) + + for sub_item in sub_items: + # Prevent recursion + if sub_item not in installed: + installed.add(sub_item) + + return installed + def installedItemCount(self): """ Return the number of stock items installed inside this one. @@ -1286,6 +1316,23 @@ class StockItem(MPTTModel): key = helpers.generateTestKey(result.test) result_map[key] = result + # Do we wish to include test results from installed items? + include_installed = kwargs.get('include_installed', False) + + # Do we wish to "cascade" and include test results from installed stock items? + cascade = kwargs.get('cascade', False) + + if include_installed: + installed_items = get_installed_items(cascade=cascade) + + for item in installed_items: + item_results = item.testResultMap + + for key in item_results.keys(): + # Results from sub items should not override master ones + if key not in result_map.keys(): + result_map[key] = item_results[key] + return result_map def testResultList(self, **kwargs):