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

Odoo中sale.order新增res.country类型Many2one字段如何设置默认值

Odoo sale.order 自定义国家字段自动取收货地址国家的实现方案

问题原因

你之前的写法未生效核心是两个问题:

  1. 字段的default默认值逻辑仅在销售订单记录首次创建初始化时执行一次,此时partner_shipping_id大概率还未赋值,自然取不到对应的国家值。
  2. 后续修改收货地址时,默认值逻辑不会重新触发,无法同步更新自定义国家字段的取值。
    第二种写法额外的错误是default=_default_country_edit()加了括号,相当于类加载阶段就直接执行了方法,此时没有实例化的订单对象,完全拿不到业务数据。

正确实现方式

需要结合@api.onchange监听收货地址字段的变化,同步更新自定义国家字段,代码示例如下:

from odoo import api, fields, models

class SaleOrder(models.Model):
    _inherit = 'sale.order'

    # 定义自定义国家字段
    country_edit = fields.Many2one('res.country', string="País")

    # 监听收货地址变化,自动更新自定义国家字段
    @api.onchange('partner_shipping_id')
    def _sync_country_edit_from_shipping(self):
        if self.partner_shipping_id and self.partner_shipping_id.country_id:
            self.country_edit = self.partner_shipping_id.country_id
        else:
            self.country_edit = False

如果需要兼容新建订单时已经预先带出收货地址的场景,可以额外补充默认值逻辑:

from odoo import api, fields, models

class SaleOrder(models.Model):
    _inherit = 'sale.order'

    def _default_country_edit(self):
        if self.partner_shipping_id and self.partner_shipping_id.country_id:
            # Many2one字段默认值返回对应记录的ID即可
            return self.partner_shipping_id.country_id.id
        return False

    country_edit = fields.Many2one(
        'res.country', 
        string="País",
        default=_default_country_edit
    )

    @api.onchange('partner_shipping_id')
    def _sync_country_edit_from_shipping(self):
        if self.partner_shipping_id and self.partner_shipping_id.country_id:
            self.country_edit = self.partner_shipping_id.country_id
        else:
            self.country_edit = False

以上实现就能达到你需要的:选择收货地址后自动带出对应国家,且用户可手动修改的效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 05:36:04