Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django grouping dictionary in a template

I have this view which is a group list for every session :

def group_list():
    attendance = Student.objects.values('session', 'group', 'full_name',).order_by('session','group')
return attendance

The dictionary look like so :

{'full_name': u'User1', 'session': 1, 'group': u'A'}
{'full_name': u'User2', 'session': 1, 'group': u"B"}
{'full_name': u'User3', 'session': 2, 'group': u"B"}
{'full_name': u'User4', 'session': 99, 'group': u'A'}
{'full_name': u'User5', 'session': 99, 'group': u"C"} 

Is there a way to make a loop or a nested loop for my template to output something like this ?

Session 1 :
    Group A
          -User1
          -...
    Group B
          -User2
Session 2 :
    Group A
    Group B
          -User3

Perhaps I did my view wrong and I should generate a slightly different dictionary already grouped by session and groups ?

like image 966
metraon Avatar asked Feb 13 '23 05:02

metraon


1 Answers

You can use regroup tag.

For example, assuming you pass attendance to template:

{% regroup attendance by session as session_list %}
{% for session in session_list %}
Session: {{ session.grouper }}
    {% regroup session.list by group as group_list %}
    {% for group in group_list %}
    Group: {{ group.grouper }}
        {% for student in group.list %}
        - {{ student.full_name }}
        {% endfor %}
    {% endfor %}
{% endfor %}
like image 105
falsetru Avatar answered Feb 15 '23 10:02

falsetru