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.

Thanks,
Dan


--~--~---------~--~----~------------~-------~--~----~
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
-~----------~----~----~----~------~----~------~--~---

Reply via email to