jinja2 groupby choice field

851 views Asked by At

In my Django model I have choice field

MY_GROUPS = [
    ('GR1', 'First Group'),
    ('GR2', 'Second Group)
]

class MyModel(models.Model):
    ...
    group = models.CharField(choices=MY_GROUPS, max_length=3)

Now I use groupby filter to display my queryset as it is explained in jinja2 docs

<ul>
{% for group in persons|groupby('group') %}
    <li>{{ group.grouper }}<ul>
    {% for person in group.list %}
        <li>{{ person.first_name }} {{ person.last_name }}</li>
    {% endfor %}</ul></li>
{% endfor %}
</ul>

But {{ group.grouper }} is a string which is field value: GR1, GR2 . How can i get my field display name as grouper string: First Group, Second Group

1

There are 1 answers

3
wencakisa On

You can use the get_FOO_display() method:

<li>{{ group.grouper.get_group_display }}<li>

Note: In templates, you don't include() in the name of a method.