I have a list of objects which form a tree structure through foreign key relationships.
parent = models.ForeignKey( 'Category', related_name = 'child_set', null = True )
So each category object has children which are also category objects. I want to pull them out of the DB in such a way as to hit the database as few times as possible. My former code looked like this:
def get_nested_categories(self):
categories = []
for child in self.child_set.all():
categories.append(child)
categories += child.get_nested_categories()
return categories
But this causes a many hits to the database and causes slowness, especially as my category list has grown beyond what I expected it to be. Is there a way to optimize this code?