On Sun, 2007-07-08 at 20:16 +0000, Dan wrote: > This question may have been asked a thousand times, but I'm not sure > how to use the Parent/Child category database model given here: > http://code.djangoproject.com/wiki/CookBookCategoryDataModelPostMagic > > I have a model Item with category as a ForeignKey. I'd like to loop > through all top level categories and then print all items in that > category or its child categories. Here's what I've got for a view: > > def catalog(request): > # Find top level categories > dict = {'categories':{}} > cats = Category.objects.all().filter(parent__isnull=True) > for cat in cats: > dict['categories'][str(cat)] = cat.getFullItemSet() > > return render_to_response('catalog.html', dict) > > And then in the Category model, I've added a function that merges all > the QuerySets from its child objects: > > def getFullItemSet(self): > items = list(self.item_set.all()) > for child in self.child_set.all(): > items.extend(child.getFullItemSet()) > return items > > This works, but it seems sloppy, and inefficient since it requires > database hits. Can anyone suggest a better way of doing this? I'll be > looking into using Q objects to filter through Item.objects.all() list > in the meantime.
Firstly, don't worry too much about the database hits. Is it provably the bottleneck in your site? Realise that "as fast as possible" is usually a needless goal. "Fast enough" is sufficient. I'm using a similar setup for blog categories (I have a hierarchical structure) and it isn't a huge performance burden. It might become so for some data setup (it's easy to imagine how), but since I don't have that sort of data at the moment, it's not worth blowing time on. Secondly, if you really want to do this in a query or two, you'll need to modify your storage structure so that you can find all the nodes in the sub-tree via a single query. Storage schemes such as nested sets, nested intervals and materialised paths all make this possible in various ways: you store auxiliary data on each node that can be used to quickly determine the position in the tree as part of the SQL query. Search for "trees and SQL" on the web for no end of articles. Once you have that sort of data structure, you can take a node, pull out all the children ids and then all the articles which have those ids. Regards, Malcolm > > Thanks, > Dan > > > > > -- What if there were no hypothetical questions? http://www.pointy-stick.com/blog/ --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to [email protected] To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~----------~----~----~----~------~----~------~--~---

