On Sep 1, 4:48 am, Stuart <stu...@bistrotech.net> wrote: > On Aug 30, 12:10 pm, graeme <graeme.piete...@gmail.com> wrote: > > > > > What my query does is give me a list of subcategories, ordered by > > category, and then by the number of places in the category, and > > annotates each subcategory with the number of places in it. > > > Having a single category model might simplify the query, but as I want > > the page to show something like: > > > CATEGORY > > Subcategory One > > Subcategory Two > > CATEGORY TWO > > Subcategory Three > > etc. > > I would take a different approach to build this structure. Take > advantage of the object model. You could get a list of root categories > and send those off to a function (probably a template filter) that > builds the html representation you want. If you have the root > categories, you have everything you need. > > root_cats = Category.objects.filter(parent__isnull=True) # gets root > categories > for cat in root_cats: # iterate thru root categories > print "%s (%s)" % (cat.name, cat.texts.count()) # CATEGORY (2) > for t in cat.texts.all(): # iterate thru texts that belong to each > root category > print t > for c in cat.children.all(): # iterate thru child categories (one > level down from the root) > print "%s (%s)" % (c.name, c.texts.count()) # Subcategory One > (3) > > Rework that code to traverse all the way to the bottom (smarter > iteration or maybe recursion) and you've got what you need without a > complicated query.
Thanks Stuart, that was a huge help, although perhaps not in the way you expected. I used the same approach with my existing models, and it works fine. The code is shorter, the queries are simpler, my template is simpler and it is a lot faster. I am currently have HTML snippets hard coded in the view which is not nice. I am not inclined to write filter or template tag, so I am thinking of moving the HTML snippets in the view into templates and using render_to_string to return strings that are then passed to the main template. > > --Stuart -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.