我从我的 View 中返回了一本字典(dict_)。在模板内我想访问特定的键。我怎样才能做到这一点?
{% for a in applications %}
{{ dict_.a.id}}
{% endfor %}
从 View 中:
context = {
'applications': applications,
'dict_': count_dict
}
return render(request, 'applications/map.html', context)
我需要连接它吗? 例如
{{ dict_ }} + {{ a.id }}
更新。这是我的观点:
def MapView(request):
applications = Application.objects.values(
'name', 'id', 'icon_name').filter(organization_id=1).order_by('name')
context = {
'applications': applications,
'devices_count': [(a, devices.filter(id=a['id']).count()) for a in applications]
}
return render(request, 'applications/map.html', context)
最佳答案
Django 的模板被故意限制,以使其不方便执行此类字典查找或进行函数调用(带参数)。原因是业务逻辑最好写在 View 中,而不是写在模板中。
例如,您可以在 View 中进行映射,例如:
context = {
<b>'app_counts': [(a, count_dict[a.id]) for a in applications]</b>
}
return render(request, 'applications/map.html', context)
然后你可以用以下方式渲染它:
{% for <b>app, count</b> in <b>app_counts</b> %}
{{ app }}: {{ count }}
{% endfor %}
关于python - 用于动态显示字典的标签串联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59930559/