| 1 | = CookBook - Template tag Regroup = |
| 2 | |
| 3 | If you need to group a list of objects by a choice like fied '''choices = CATEGORY_CHOICES''', |
| 4 | here is the trick. |
| 5 | |
| 6 | A Model. |
| 7 | {{{ |
| 8 | #!python |
| 9 | |
| 10 | CATEGORY_CHOICES = ( |
| 11 | (1, 'Entrées'), |
| 12 | (2, 'Poissons et crustacés'), |
| 13 | (3, 'Viandes et volailles'), |
| 14 | (4, 'Légumes et accompagnements'), |
| 15 | (5, 'Desserts'), |
| 16 | (6, 'Boissons'), |
| 17 | (8, 'Autres'), |
| 18 | ) |
| 19 | |
| 20 | class Recette(meta.Model): |
| 21 | [...] |
| 22 | categorie = meta.SmallIntegerField(choices = CATEGORY_CHOICES) |
| 23 | |
| 24 | }}} |
| 25 | |
| 26 | The Rrgroup tag in action, the thing is that you don't want to display the category |
| 27 | number bit its corresponding name. (e.g not '1' but 'Entrées'). |
| 28 | |
| 29 | Temmplate |
| 30 | {{{ |
| 31 | #!python |
| 32 | |
| 33 | {% regroup recettes by categorie as grouped %} |
| 34 | <ul> |
| 35 | {% for group in grouped %} |
| 36 | <li>{{ group.list.0.get_categorie_display }} |
| 37 | <ul> |
| 38 | {% for item in group.list %} |
| 39 | <li>{{ item }}</li> |
| 40 | {% endfor %} |
| 41 | </ul> |
| 42 | {% endfor %} |
| 43 | </ul> |
| 44 | |
| 45 | }}} |