Django:无法访问模板中字典的值

时间:2019-01-29 10:22:16

标签: python django

我有一个包含以下代码的视图:

@login_required
def grouping(request, project_id):
    groups = {}
    order = {}

    # Bind parameters to variables and return a 404 if one is considered incorrect
    for i in range(1, 5):
        if request.GET.get('filter%i' % i, None) is not None:
            try:
                order[i] = int(request.GET.get('filter%i' % i, None))
            except ValueError:
                return projects_overview(request, 'Incorrect filter parameters passed', 404)

    if order == {}:
        return projects_overview(request, 'Incorrect filter parameters passed', 404)

    original_properties = []

    # Put all of the originally passed properties in a list
    for key in order:
        property = Property.objects.get(pk=order[key])
        original_properties.append(property)

    # Get the corresponding category and project
    category = original_properties[0].category
    project = Project.objects.get(pk=project_id)

    objects = Object.objects.filter(project=project, type__category=category)

    # Group the objects with the same property values together
    for object in objects:
        properties = object.property_set.all().order_by('name')
        values = []
        for property in properties:
            if property.original_property in original_properties:
                values.append(property.value)
        values_json = json.dumps(values)
        if groups.get(values_json) is None:
            groups[values_json] = []
        groups[values_json].append(object)
    print(groups)

    return render(request, 'dashboard/groups.html', {'groups': groups, 'project': project,
                                                     'function_create_form': ObjectForm(project_id=project_id)})

问题出在变量groups上,它返回如下内容:

{'["a", "b", "c"]': [<Object: Object 3>, <Object: Object 4>], '["q", "w", "e"]': [<Object: Object 5>]}

现在,我正在尝试在模板中对此进行迭代:

{% for group in groups %}
    {{ group }}
{% endfor %}

这给了我键,这很有意义:

["a", "b", "c"] ["q", "w", "e"]

但是实际上,我只关心键上附加的列表。所以我这样做:

{% for key, group in groups %}
    {{ key }}
    {{ group }}
{% endfor %}

这给了我以下错误: Need 2 values to unpack in for loop; got 15.

所以我尝试了这个,但这只是给了我一个按键,就像我已经期望的那样:

{% for group in groups %}
    {% for object in group %}
        {{ object }}
    {% endfor %}
{% endfor %}

我以前从未遇到过这个问题,这与我构建字典的方式有关吗?

2 个答案:

答案 0 :(得分:2)

要遍历字典中的键值对,请使用items方法。

{% for key, group in groups.items %}
    {{ key }}
    {{ group }}
{% endfor %}

如果只需要这些值,请使用values

{% for group in groups.values %}
    {{ group }}
{% endfor %}

答案 1 :(得分:1)

对于Python 2.x:

for key, value in groups.iteritems():
    {{ key }}
    {{ value }}

对于Python 3.x:

for key, value in groups.items():
    {{ key }}
    {{ value }}