You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Odoo17 Qweb报表中如何按类别循环展示分组产品列表?

Odoo17 Qweb报表:按类别展示分组产品列表问题解决

问题描述

在Odoo17的Qweb报表中,需要按类别展示分组后的产品列表。已在Python类中生成如下结构的字典数据:

{
    'Office Furniture': 
    [
        {'name': 'Chair floor protection\nOffice chairs can harm your floor: protect it.', 'cat': 'Office Furniture'}, 
        {'name': 'Chair floor protection\nOffice chairs can harm your floor: protect it.', 'cat': 'Office Furniture'}
    ], 
    'Services': 
    [
        {'name': 'Deposit', 'cat': 'Services'}
    ]
}

但当前Qweb代码仅能显示类别名称,无法遍历展示对应类别的产品:

<div>
    <t t-foreach="data['purchases']" t-as="category">
        <p>
            <!-- Display the category : WORKS FINE -->
            <span t-esc="category" />
            <t t-foreach="category" t-as="product">
                <!-- Display the product : HOW ? -->
            </t>
        </p>
    </t>
</div>

问题原因

当使用t-foreach遍历字典时,默认迭代的是字典的键,此时category变量存储的是类别名称字符串(如'Office Furniture'),而非该类别对应的产品列表。直接遍历category相当于遍历字符串的每个字符,自然无法正确展示产品。

解决方案

遍历字典的键时,通过字典键值对的方式获取对应类别的产品列表,即使用data['purchases'][category]作为内层遍历的数据源。

修正后的Qweb代码如下:

<div>
    <t t-foreach="data['purchases']" t-as="category">
        <div class="category-section">
            <!-- 显示类别名称 -->
            <h3 t-esc="category" />
            <!-- 遍历当前类别下的产品列表 -->
            <t t-foreach="data['purchases'][category]" t-as="product">
                <p t-esc="product['name']" />
                <!-- 若需展示产品其他字段,可按需添加,例如 -->
                <!-- <span t-esc="product['cat']" /> -->
            </t>
        </div>
    </t>
</div>

补充优化方案

若希望同时获取字典的键和值,也可以使用字典的items()方法,此时遍历的每个元素是包含键和值的元组,Qweb中可通过category_item[0]获取类别名称,category_item[1]获取产品列表:

<div>
    <t t-foreach="data['purchases'].items()" t-as="category_item">
        <div class="category-section">
            <h3 t-esc="category_item[0]" />
            <t t-foreach="category_item[1]" t-as="product">
                <p t-esc="product['name']" />
            </t>
        </div>
    </t>
</div>

内容的提问来源于stack exchange,提问作者Arthur Fortin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 22:07:21