Django - 在模板中打印字典

Django - Print dict in template

我有一个字典的字典 my_var 定义为:

defaultdict(<class 'collections.Counter'>,{
    'product1': Counter({'total_qty': 1}),
    'product2': Counter({'total_qty': 13}),
    'product3': Counter({'total_qty': 65})
})

我将它传递给模板:

context = {'my_var': my_var}
return render(request, 'my_template.html', context)

在模板中,我尝试打印它但没有任何运气:

<ul>
    {% for k in my_var %}
        <li>{{ k.component }}: {{ k.total_qty }}</li>
    {% endfor %}
</ul>

我没有收到任何错误,但是我没有得到键和值;我做错了什么?

我得到类似的东西:

编辑:

为了添加一些上下文,我最初有一个字典列表:

used_components = [{'total_qty': 5, 'component': 'component blue'},...]

然后我使用这个函数按键对字典进行分组和求和:

def solve(dataset, group_by_key, sum_value_keys):
    dic = defaultdict(Counter)
    for item in dataset:
        key = item[group_by_key]
        vals = {k: item[k] for k in sum_value_keys}
        dic[key].update(vals)
    return dic

my_var = solve(used_components, 'component', ['total_qty'])

然后我尝试在模板中打印 my_var,如上所述。

编辑2:

这是我的真实 views.py:

def solve(dataset, group_by_key, sum_value_keys):
    dic = defaultdict(Counter)
    for item in dataset:
        key = item[group_by_key]
        vals = {k: item[k] for k in sum_value_keys}
        dic[key].update(vals)
    return dic

def components_by_season(request, season_name):
    season = get_object_or_404(Season, name=season_name)

    orderitems = OrderItem.objects.filter(order__season__name=season_name)

    # variant_ids = OrderItem.objects.filter(order__season__name=season_name).values_list('variant_id', flat=True)
    # components = Component.objects.filter(bom__variant__id__in=variant_ids)

    used_components = []

    for item in orderitems:
        variant_ordered_qty = item.qty
        components = Component.objects.filter(boms__variant__id__exact=item.variant.id)
        for component in components:
            bom_qty = component.boms.get(component=component).qty
            total_qty = bom_qty * variant_ordered_qty
            used_components.append({
                'component': component.name.encode('ascii', 'ignore'),
                'total_qty': total_qty
            })

    out = solve(used_components, 'component', ['total_qty'])

    # counter = Counter(used_components)

    context = {'season': season, 'orderitems': orderitems, 'used_components': used_components, 'out': out}
    return render(request, 'components_by_season.html', context)

假设这实际上是您的真实代码,my_var 是一个命令,而不是一个列表。遍历一个字典只会给你钥匙;如果你也想要这些值,你应该遍历 .items()。所以:

<ul>
    {% for k, v in my_var.items %}
        <li>{{ k }}: {{ v.total_qty }}</li>
    {% endfor %}
</ul>

另请注意,没有 product 键;产品名称只是外字典中的关键字。

最后我通过将 out.items() 传递给模板并遍历 out 使其工作,所以:

views.py

context = {'out': out.items()}
return render(request, 'components_by_season.html', context)

在我的模板中:

{% for k,v in out %}
    <p>{{ k }}: {{ v.total_qty }}</p>
{% endfor %}

如果你只是想打印这个来调试,你可以使用 pprint filter:

{{out|pprint}}