Django - 在模板中打印字典

时间:2017-03-26 14:44:01

标签: django django-templates django-1.10

我将dicts 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>

我没有得到任何错误,但我没有获得密钥和值;我做错了什么?

我得到类似的东西:

编辑:

添加一些上下文,我最初有一个dicts列表:

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,如上所述。

EDIT2:

这是我的实际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)

2 个答案:

答案 0 :(得分:2)

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

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

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

答案 1 :(得分:0)

最后,我通过将git.getRepository().getWorkTree().delete()传递给模板并迭代out.items()来实现它,所以:

views.py

out

在我的模板中:

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