Wednesday, August 31, 2011

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

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.


--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+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment