【问题标题】:Output list by key in django template在 django 模板中按键输出列表
【发布时间】:2020-05-12 16:57:55
【问题描述】:

我从视图中返回一个列表,我想在模板中按键输出具体的值。

返回列表(list_)

[
{'category 1': 1},
{'category  2': 3},
{'category 3': 4}, 
]

在模板中:

{{ list_.2.category 3}}

返回 4。

可以让模板标签更简单,直接按键输出吗?

例如:

{{ list_.key['category 3'] }}

我的看法:

def MapView(request):
    applications = Application.objects.values(
        'name', 'id', 'icon_name').filter(organization_id=1).order_by('name')
    devices = Device.objects.all()
    count_list = []

    for a in applications:
        count_num = devices.filter(id=a['id']).count()
        count_list.append({
            a['name']: count_num
        })

    context = {
        'test': count_list,
    }

    return render(request, 'applications/map.html', context)

【问题讨论】:

    标签: python django django-templates


    【解决方案1】:

    dictlist 转换为dict

    例如:

    from collections import ChainMap
    
    list_ = [{'category 1': 1}, {'category  2': 3}, {'category 3': 4}]
    list_ = dict(ChainMap(*list_))
    print(list_)
    

    在模板中:

    {{ list_.category 3}}
    

    注意:我假设您有唯一的键。


    看来你可以使用collections.defaultdict

    例如:

    from collections import defaultdict
    
    def MapView(request):
        applications = Application.objects.values(
            'name', 'id', 'icon_name').filter(organization_id=1).order_by('name')
        devices = Device.objects.all()
        count_list = defaultdict(int)
    
        for a in applications:
            count_list[a['name']]+= devices.filter(id=a['id']).count()
    
        context = {
            'test': count_list,
        }
    
        return render(request, 'applications/map.html', context)
    

    【讨论】:

    • 我已经添加了我的视图,我想我可以将其更改为字典。我只想将项目附加到它。这就是我使用列表的原因
    • 完美。你回答了我的问题。一张小纸条。我需要将列表与循环中的另一个字段连接起来。例如test.a.name a.name 是循环迭代值。 for a in applications
    【解决方案2】:

    您可以从视图中返回字典,并更方便地访问键值。

    例如。

    context = {
        'category 1': 1,
        'category  2': 3,
        'category 3': 4
    }
    return render(request, 'polls/index.html', context)
    

    你可以像这样在你的模板中访问它 -

    {for key, value in context}
    <li> {{ value }} </li> 
    

    <li> {{ context[key] }} </li>
    

    【讨论】:

      【解决方案3】:

      您不能在模板中使用方括号,但您可以创建自定义simple tag

      @register.simple_tag(name=access_lst)
      def access_list_of_dicts(lst, index, key):
         return lst[index].get(key)
      

      并在模板中使用它:

      {% access_lst list 2 "category 3" %}
      

      【讨论】:

        猜你喜欢
        • 2010-11-21
        • 2013-11-13
        • 2011-06-06
        • 2018-11-15
        • 1970-01-01
        • 2012-11-06
        • 1970-01-01
        • 2014-03-14
        相关资源
        最近更新 更多