gadss
gadss

Reputation: 22489

Grouping then sorting in template django

I have these code in my views.py:

array = []
p = Person.objects.filter(client=1,status='Complete').values('name', 'age', 'category').order_by('category')
for x in p:
 d = {'Name': x['name'], 'Age': x['age'], 'Category':x['category']}
 array.append(d)

then i got these :

[{'Name': u'Mike', 'Age': 20, 'Category':'A'},
{'Name': u'Bell', 'Age': 30, 'Category':'A'},
{'Name': u'Ned', 'Age': 23, 'Category':'B'},
{'Name': u'Ben', 'Age': 21, 'Category':'B'},
{'Name': u'Tom', 'Age': 28, 'Category':'B'},]

in my template:

{% if persons %}
 {% for p in persons %}
   Category {{p.Category}} :<br>{{p.Name}} <br> {{p.Age}}
 {% endfor %}
{% endif %}

I really want to be out-put is like this:

Category A:
Mike 20
Bell 30

Category B:
Ned 23
Ben 21
Tom 28

do anyone have an idea about my case? thanks in advance ...

Upvotes: 1

Views: 275

Answers (1)

Timmy O&#39;Mahony
Timmy O&#39;Mahony

Reputation: 53971

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 %}

Upvotes: 2

Related Questions