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

如何在Odoo数据透视视图(Pivot View)中为列设置颜色?

在Odoo数据透视视图中按字段值设置颜色的方法

Odoo默认的pivot视图没有内置的颜色规则配置,需要通过自定义代码实现,以下是几种常用方案:

方案一:重写Pivot渲染组件全局生效

这种方式会对所有pivot视图生效,适合设置全局统一的颜色规则:

  1. 创建自定义JS文件
    在模块的static/src/js/目录下新建pivot_color.js,内容如下:
odoo.define('your_module.pivot_color', function(require) {
    "use strict";

    const PivotRenderer = require('web.PivotRenderer');
    const registry = require('web.field_registry');

    const CustomPivotRenderer = PivotRenderer.extend({
        _renderCell: function(cell) {
            const $cell = this._super(...arguments);
            // 仅针对数值型字段处理
            if (cell.value !== null && typeof cell.value === 'number') {
                // 根据数值范围添加Odoo内置样式类
                if (cell.value > 1000) {
                    $cell.addClass('bg-danger text-white');
                } else if (cell.value < 100) {
                    $cell.addClass('bg-success text-white');
                } else {
                    $cell.addClass('bg-secondary text-white');
                }
            }
            return $cell;
        },
    });

    registry.add('pivot', CustomPivotRenderer);
    return CustomPivotRenderer;
});
  1. 在模块清单中引入JS
    修改__manifest__.py,将JS添加到后端资源中:
{
    # ... 其他清单配置
    'assets': {
        'web.assets_backend': [
            'your_module/static/src/js/pivot_color.js',
        ],
    },
}
  1. 升级模块生效
    在Odoo后台升级你的自定义模块,刷新页面后所有pivot视图的数值单元格会按规则变色。

方案二:针对特定模型/视图局部修改

如果只想给某一个模型的pivot视图设置颜色,可以在JS中添加模型判断:
修改方案一中的JS代码,在_renderCell方法开头加入判断逻辑:

// 仅对sale.order模型的pivot视图生效
if (this.state.model !== 'sale.order') {
    return $cell;
}

方案三:纯CSS快速实现(版本兼容性差)

如果不想编写JS,可尝试通过CSS选择器匹配字段值,比如针对sale.order的amount_total字段:
在模块的static/src/css/pivot_color.css中添加:

/* 匹配金额大于1000的单元格 */
.o_pivot_table .field-amount_total .o_pivot_cell:has(> .o_pivot_value:not(:contains("-")):not(:contains("0"))) {
    background-color: #ff4444;
    color: white;
}

同样需要在__manifest__.py中引入CSS文件,这种方法缺点是依赖Odoo的DOM结构,版本更新后可能失效。

内容的提问来源于stack exchange,提问作者Jaypal Maru

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 07:40:40