views:

33

answers:

2

I have a "Category" model, and a "Project" model, which contains a ForeignKey to "Category." So each Project can only belong to one Category.

I want to create a list that ends up looking like the following:

Category 1
Project 1
Project 2

Category 2
Project 3
Project 4

etc.

I think the following psuedocode will work:

<ul class="category-list">
{% for c in category %}
    <li>{{ c.title }}</li>
    <ul class="project-list">
        {% for p in project WHERE CATEGORY = C %}
            <li>{{ p.title }}</li>
        {% endfor %}
    </ul>
{% endfor %}
</ul>

The part I'm having trouble with is the "WHERE CATEGORY = C" part. How do I express this in Django template code?

+1  A: 

You can do this by using the regroup tag http://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#regroup

txwikinger
Thanks, this worked perfectly.
Desmond
+1  A: 
{% for p in c.project_set.all %}

Look in the Django documentation for following relationships backwards.

Daniel Roseman