How to render an ordered dictionary in django templates?

后端 未结 4 374
情书的邮戳
情书的邮戳 2021-01-31 14:58

I\'m trying to learning django templates but it\'s not easy.
I have a certain views.py containing a dictionary to be rendered with a template. The dictionary is made of ke

4条回答
  •  迷失自我
    2021-01-31 16:02

    Refreshing old question but it was something that I've spent some time on as a programming noobie. It kinds of expands Yuji Tomita's answer.

    How to sort dictionary that looks like this:

    {model_A_object: {key: value, ...},...}
    

    by model_A_object.field.

    I fill it with for loop, and use it to store some aggregation, etc., data for queryset that I pass to template.

    I've managed to do this (with Shubuntu from #Django help) by:

        result = sorted(dictionary.iteritems(), key= lambda (k, v) :  (k.field, v))
    

    Then in the template:

        {% for model_A_object, data in result %}
            {% for key, value in data.items %}
                ...
            {% endfor %}
        {% endfor %}
    

    Clean and easy, yet not that simple to figure out for beginner. Notice, that first for loop has result not result.items as it's not dictionary anymore, but list of tuples.

    Hope it helps someone.

提交回复
热议问题