Django模板未遍历对象

时间:2019-04-12 02:09:57

标签: python django

我正在使用Django渲染项目菜单。我可以得到我想要的内容,但是当我将其返回到django模板时,它只是一个json字符串,因此不会正确迭代。如何告诉django将其作为可迭代对象返回?

我遇到了this article。也许我想合并查询集?

Python

def index(request):
    if not request.user.is_authenticated:
        return redirect('/login', {'message': None})
    try:
        menu_categories = MenuCategory.objects.all()
        menu = []
        for cat in menu_categories:
            items = MenuCategoryItems.objects.filter(category_id=cat.id).all()
            menu.append({'category': cat, 'items': items})
        context = {'menu': menu}
        # for cat in menu_categories:
        #     items = menu_items.filter(category_id=cat.id)
        #     category_items = []
        #     for item in items:
        #         category_items.append({
        #             "name": item.name,
        #             "price": float(item.price),
        #             "id": item.id
        #         })
        #     menu.append({"category": cat.name, "items": category_items})

    except Exception:
        print('failure')

    return render(request, 'index.html', context)

模板

            {% for category in menu %}
                <div>{{ category.name }}</div>
{#                {% for item in category.items %}#}
{#                    <div>{{ item.name }} | {{ item.price }}</div>#}
{#                {% endfor %}#}
            {% endfor %}

1 个答案:

答案 0 :(得分:0)

我想我找到了答案。这对我有用,但是我不确定这是否是“首选”方式。

Python

def index(request):
    if not request.user.is_authenticated:
        return redirect('/login', {'message': None})
    try:
        menu_categories = MenuCategory.objects.all()
        menu = []
        for cat in menu_categories:
            items = MenuCategoryItems.objects.filter(category_id=cat.id).all()
            menu.append({'category': cat, 'items': items.values})
        context = {'menu': menu}
    except Exception:
        print('failure')

    return render(request, 'index.html', context)

模板

    {% for category in menu %}
        <div><strong>{{ category.category.name }}</strong></div>
        {% for item in category.items %}
            <div>{{ item.name }} - {{ item.price }}</div>
        {% endfor %}
    {% endfor %}