Wednesday, August 31, 2011

Re: Combining queries? A "join" in Python?

On Aug 30, 12:10 pm, graeme <> 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:
> Subcategory One
> Subcategory 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
for cat in root_cats: # iterate thru root categories
print "%s (%s)" % (, 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.texts.count()) # Subcategory One

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.


You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to
To unsubscribe from this group, send email to
For more options, visit this group at

No comments:

Post a Comment