2👍
This code is incredibly inefficient. It will do a new series of database queries for every single category, and for each category’s ancestor.
You need to look into the algorithms that are optimised for storing and retrieving this sort of hierarchical data in a database. django-mptt is my favourite of these.
As an aside, it is also inefficient to repeatedly insert elements at the start of a list. Lists are optimised for appending, they are not optimised for inserting. A data structure optimised for adding at both ends is the deque
in Python’s collections
module – but a better solution would probably be to simply append the elements, then call reverse()
on the list before returning it.
Source:stackexchange.com