Commit ead2f182 authored by Kenzo-Hugo Hillion's avatar Kenzo-Hugo Hillion
Browse files

Optimise to not have to build hierarchy everytime

parent 0345bdf9
Pipeline #17572 passed with stages
in 2 minutes and 32 seconds
......@@ -15,6 +15,6 @@ class TaxonomyViewSet(BulkViewSet):
def retrieve(self, request, *args, **kwargs):
instance = self.get_object()
instance.build_parental_hierarchy()
hierarchy = instance.parental_hierarchy # noqa
serializer = self.get_serializer(instance)
return Response(serializer.data)
......@@ -97,11 +97,33 @@ class Taxonomy(models.Model):
def __str__(self):
return f"{self.name}"
def build_parental_hierarchy(self):
@property
def parental_hierarchy(self):
if self.kingdom is None and self.superkingdom is None:
return self._build_parental_hierarchy()
return self._dict_parental_hierarchy()
def _dict_parental_hierarchy(self):
"""
Return parental hierarchy from
"""
ranks = [
"superkingdom", "kingdom", "phylum", "class_rank", "order", "family", "genus", "species"
]
hierarchy = {}
for rank in ranks:
if getattr(self, rank, None) is not None:
hierarchy[rank] = getattr(self, rank)
return hierarchy
def _build_parental_hierarchy(self):
"""
Build and save parental hierarchy for an entry
"""
hierarchy = {}
if self.name != 'root' and self.parent is not None:
hierarchy[self.rank] = self
hierarchy = {**hierarchy, **self.parent.build_parental_hierarchy()}
hierarchy = {**hierarchy, **self.parent.parental_hierarchy}
for level, value in hierarchy.items():
setattr(self, level, value)
self.save()
......
......@@ -33,6 +33,9 @@ class TestBuildHierarchy(APITestCase):
'kingdom': self.kingdom
}
self.assertNotEqual(getattr(self.phylum, 'kingdom', None), self.kingdom)
test_dict = self.phylum.build_parental_hierarchy()
test_dict = self.phylum.parental_hierarchy
self.assertDictEqual(test_dict, expected_dict)
self.assertEqual(getattr(self.phylum, 'kingdom', None), self.kingdom)
# Now try a second time from saved information
test_dict = self.phylum.parental_hierarchy
self.assertDictEqual(test_dict, expected_dict)
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment