[Answered ]-Grouping then sorting in template django

2๐Ÿ‘

โœ…

You can use the regroup template tag

{% if persons %}
    {% regroup persons by "Category" as people_list %}
    {% for key, val in people_list.items %}
        {{ key|title }} : <br /> {{ val|title }}
    {% endfor %}
{% endif %}

Note that values :

Returns a ValuesQuerySet โ€” a QuerySet subclass that returns dictionaries when used as an iterable, rather than model-instance objects.

so you can remove this:

for x in p:
    d = {'Name': x['name'], 'Age': x['age'], 'Category':x['category']}
    array.append(d)

and change the regroup to:

{% regroup persons by category as people_list %}
๐Ÿ‘คTimmy O'Mahony

Leave a comment