Code


Version 1 (modified by anonymous, 8 years ago) (diff)

--

CookBook - Template tag Regroup

If you need to group a list of objects by a choice like fied choices = CATEGORY_CHOICES, here is the trick.

A Model.

CATEGORY_CHOICES = (
        (1, 'Entrées'),
        (2, 'Poissons et crustacés'),
        (3, 'Viandes et volailles'),
        (4, 'Légumes et accompagnements'),
        (5, 'Desserts'),
        (6, 'Boissons'),
        (8, 'Autres'),
)       

class Recette(meta.Model):
        [...]
        categorie = meta.SmallIntegerField(choices = CATEGORY_CHOICES)

The Rrgroup tag in action, the thing is that you don't want to display the category number bit its corresponding name. (e.g not '1' but 'Entrées').

Temmplate

{% regroup recettes by categorie as grouped %}
<ul>
{% for group in grouped %}
        <li>{{ group.list.0.get_categorie_display }} 
    <ul>
        {% for item in group.list %}
        <li>{{ item }}</li>
        {% endfor %}
    </ul>
{% endfor %}
</ul>