简体   繁体   中英

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM