确定循环的django模板中的迭代顺序

确定循环的django模板中的迭代顺序,django,for-loop,django-templates,Django,For Loop,Django Templates,我正在填充视图中的列表: hits_object = {} hits_object['Studio'] = hitlist('Studio',days) hits_object['Film'] = hitlist('Film',days) hits_object['Actor'] = hitlist('Actor',days) hits_object['Historical Event'] = hitlist('Event',days) hits_object['Pop Culture'] =

我正在填充视图中的列表:

hits_object = {}
hits_object['Studio'] = hitlist('Studio',days)
hits_object['Film'] = hitlist('Film',days)
hits_object['Actor'] = hitlist('Actor',days)
hits_object['Historical Event'] = hitlist('Event',days)
hits_object['Pop Culture'] = hitlist('Pop_Culture',days)
然后,我将其显示在我的模板中:

{% for model, hits in hits_object.items %}
    {% if hits %}
        <u> Most {{ model }} views in last {{ days }} days</u>
            <ol>
                {% for hit in hits %}
                    <li>{{ hit.name }} - {{ hit.count }}</li>
                {% endfor %}
            </ol>
        </u>
    {% endif %}
{% endfor %}
{%对于模型,在hits_object.items%}
{%if hits%}
过去{{days}}天内的大多数{{model}}视图
{命中率为%的命中率%}
  • {{hit.name}}-{hit.count}
  • {%endfor%} {%endif%} {%endfor%}
    问题是模型的显示顺序似乎是随机的:首先是演员,然后是工作室、历史事件、电影等等


    如何强制模板中的for循环以特定顺序迭代对象?

    字典是无序的。如果需要保留插入顺序,请使用有序的dict实现,例如,
    django.utils.datastructures.SortedDict
    中有一个


    或者,由于您似乎没有使用字典的键,而只是反复浏览,因此添加到简单列表似乎更容易。

    正如Daniel所解释的,字典是随机访问的。这里有一种方法可以满足您的需求:

    hits_object = list()
    hits_objects.append(
           (hitlist('Studio',days),
            hitlist('Film',days),
            hitlist('Actor',days),
            hitlist('Event',days),
            hitlist('Pop_Culture',days))
    
    在你看来:

    {% for studio,film,actor,event,pop_culture in hits_objects %}
          # do something...
    {% endfor %}