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

Odoo 18:如何程序化筛选analytic_distribution组件中的分析账户?

Odoo 18企业版采购订单行analytic_distribution组件分析账户筛选方案

配置回顾

  • 模型global.budget:包含允许的account.analytic.account列表;
  • 模型purchase.order:拥有指向global.budget的overall_budget_id字段;
  • 目标:采购订单行的analytic_distribution组件仅显示关联预算中定义的分析账户。

问题分析

Odoo 18的analytic_distribution基于OWL组件开发,调用的是search_read接口而非传统的search/name_search方法,导致常规重写钩子失效。

已尝试无效方案

  1. XML注入上下文:未正确传递层级关联的ID列表,且组件未捕获上下文参数;
  2. 重写account.analytic.account的search/name_search:组件未触发该类方法。

有效解决方案

步骤1:添加采购订单计算字段

在purchase.order模型中添加计算字段,关联预算允许的分析账户:

from odoo import models, fields, api

class PurchaseOrder(models.Model):
    _inherit = 'purchase.order'

    allowed_analytic_account_ids = fields.Many2many(
        'account.analytic.account',
        compute='_compute_allowed_analytic_account_ids',
        store=False,
    )

    @api.depends('overall_budget_id')
    def _compute_allowed_analytic_account_ids(self):
        for order in self:
            order.allowed_analytic_account_ids = order.overall_budget_id.allowed_analytic_account_ids

步骤2:重写分析账户的search_read方法

组件调用search_read接口获取数据,在此处注入筛选逻辑:

class AccountAnalyticAccount(models.Model):
    _inherit = 'account.analytic.account'

    @api.model
    def search_read(self, domain=None, fields=None, offset=0, limit=None, order=None):
        allowed_ids = self.env.context.get('allowed_analytic_account_ids')
        if allowed_ids:
            domain = domain or []
            # 合并允许账户ID的筛选条件
            domain = [('id', 'in', allowed_ids)] + domain
        return super().search_read(domain=domain, fields=fields, offset=offset, limit=limit, order=order)

步骤3:调整XML视图传递上下文

确保采购订单行的analytic_distribution字段能获取到父订单的允许账户ID列表:

<record id="purchase_order_form_analytic_filter" model="ir.ui.view">
    <field name="name">purchase.order.form.analytic.filter</field>
    <field name="model">purchase.order</field>
    <field name="inherit_id" ref="purchase.purchase_order_form"/>
    <field name="arch" type="xml">
        <!-- 隐藏用于传递数据的允许账户字段 -->
        <xpath expr="//sheet" position="inside">
            <field name="allowed_analytic_account_ids" invisible="1"/>
        </xpath>
        <!-- 给订单行的analytic_distribution传递上下文ID列表 -->
        <xpath expr="//field[@name='order_line']/tree//field[@name='analytic_distribution']" position="attributes">
            <attribute name="context">{'allowed_analytic_account_ids': parent.allowed_analytic_account_ids.ids}</attribute>
        </xpath>
    </field>
</record>

关键说明

  • XML选项键:analytic_distribution组件支持通过options传递静态domain,但动态筛选必须结合上下文+Python重写;
  • 上下文传递层级:订单行视图中需用parent.allowed_analytic_account_ids.ids获取父订单的允许账户ID列表,需匹配视图层级结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.01 13:27:35