0

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?

Alasdair
  • 298,606
  • 55
  • 578
  • 516

1 Answers1

0

This is not a Django ORM problem, but rather a lower-level relational modeling problem. Check out this related question on nested sets and adjacency lists for a good overview of your options in a relational database. Short of that you could pursue a document-oriented (NoSQL) strategy for this particular data structure.

Community
  • 1
  • 1
Joe Holloway
  • 28,320
  • 15
  • 82
  • 92