【问题标题】:Nested loop to access dictionary Django HTML嵌套循环访问字典 Django HTML
【发布时间】:2019-11-07 10:38:54
【问题描述】:

我有这样的列标题列表:

ColumnName = ['Latitude', 'Longitude', 'Depth']

还有一个格式如下的字典:

MyDict = [{'Latitude': '75',
           'Longitude': '37',
           'Depth': 6.0},
          {'Latitude': '23',
           'Longitude': '97',
           'Depth': 2.3},
          {'Latitude': '55',
           'Longitude': '14',
           'Depth': 1.9}]

我想用该数据制作动态表,并通过列表中的键访问字典值。我已经尝试在我的 django HTML 中使用此代码,但它不起作用

<table>
<thead>
    <tr>
        {% for ColName in ColumnName %}
            <th> ColName <th>
        {% endfor %}
    <tr>
</thead>
<tbody>
        {% for i in MyDict %}
            <tr>
            {% for x in ColumnName %}
                <td>
                     {{i.x}}
                </td>
            {% endfor %}
            </tr>
        {% endfor %}
</tbody>
</table>

如果我使用

{{i.Latitude}}

它可以工作,但如果我使用 {{i.x}} 访问该数据,它就不起作用

【问题讨论】:

    标签: django loops for-loop django-templates nested


    【解决方案1】:

    最简单的解决方案是使用(latitude, longitude, depth) 元组列表而不是字典列表。在你看来

    def myview(request):
        the_dicts = get_the_dicts()
        # pep 08: variables should be all_lower + use plural for collections
        columns = ['Latitude', 'Longitude', 'Depth'] 
        data = [tuple(d[name] for name in column_names]) for d in the_dicts]
        return render(request, "yourtemplate.html", {"columns": columns, "data":data})
    

    在你的模板中:

    <table>
    <thead>
        <tr>
            {% for colname in columns %}
                <th> colname <th>
            {% endfor %}
        <tr>
    </thead>
    <tbody>
            {% for row in data %}
                <tr>
                {% for value in row %}
                    <td>{{value}}</td>
                {% endfor %}
                </tr>
            {% endfor %}
    </tbody>
    </table>
    

    替代方案(如果你真的想使用字典列表)需要编写一个自定义模板过滤器或模板标签来进行动态字典查找,但这更复杂并且可能也慢得多(3个标签或过滤器调用列表中的每个 dict == 显着开销)。

    【讨论】:

      【解决方案2】:

      你可以试试类似的东西

      {% for key, values in myDict.items %}
      

      【讨论】:

      • 字典不保证在 python 3.7.something 之前订购
      • @brunodesthuilliers 啊是的,这是真的。我一开始想只对 colname 和 value 使用 dict,但现在我看到了,它会重复键。
      • 你能解释一下为什么要试试这个吗?这段代码如何解决问题?请记住,其他人应该能够从您的代码中学习
      猜你喜欢
      • 2021-12-19
      • 2023-01-25
      • 2017-07-22
      • 2022-06-15
      • 2022-08-17
      • 2021-11-07
      • 1970-01-01
      • 2020-09-13
      相关资源
      最近更新 更多