python - 用于动态显示字典的标签串联

标签 python django django-templates

我从我的 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/

相关文章:

python - Django SQL 查询重复 n 次

php - php 中的数组和 python 中的 dict 是一样的吗?

python - 如何在Django中制作删除按钮

django - 如何实现投票验证系统?

django 表如何检测表是否为空

python - 如何将 forloop.counter 连接到我的 django 模板中的字符串

python - 使用 Python 将 Perl 模块转换为 JSON

python - tensorflow 的非线性回归

python - 使用 ArtistAnimation 在 matplotlib 中动画化 png

python - 上面的异常(没有这个表: oauth2_provider_accesstoken) was the direct cause of the following exception: