Skip to content

10. 模型关系 ​

适用版本

Odoo 20 社区版 · 对应官方文档 Chapter 7(Relations between models)

第 10 课:模型关系 ​

10.1 目标 ​

正常真实业务里没有孤立的数据:一条房源记录有类型、有标签、有多条买家出价。这一课主要解决下面三个问题:

  1. 三种关系字段分别在哪张表里体现(有一个表不需要建列);
  2. 为什么 offer_ids = [1, 2] 这种写法会报错,必须用 Command;
  3. ondelete 配错会带来什么后果?

10.2 Odoo 的模型关系 ​

10.2.1 三种关系和三种落库方式 ​

字段关系定义在哪数据库里的样子
Many2one多的一方本表一列存对方 id(外键)
One2many一的一方不建列,靠对方表的那个 Many2one 反查
Many2many任意一方单独一张中间表,两列都存 id

理解这张表能省很多疑惑:

  • One2many 是"虚拟字段",删掉它,数据不会变少,因为关系本来就存在对方表里;
  • Many2many 的中间表名是两张表名按字母序拼接 + _rel,比如 estate.property 与 estate.property.tag 拼出 estate_property_estate_property_tag_rel;
  • 因此同两张表之间的多个 m2m 字段会共用一张中间表(列名不同),想分开就显式指定 relation。

10.2.2 一对多要在两边模型各写一次 ​

One2many 和 Many2one 是同一个关系的两面,必须成对出现:

python
# 在出价表 offer(多的一方)
property_id = fields.Many2one('estate.property', string='房源', required=True, ondelete='cascade')

# 在房源表 property(一的一方)
offer_ids = fields.One2many('estate.property.offer', 'property_id', string='出价')

One2many 的第二个参数必须是对方那个 Many2one 的字段名,写错不会报错,只是永远空。

10.2.3 ondelete:删父记录时子记录怎么办 ​

取值行为适用
set null子记录的外键置空可选关联,如"类型"
cascade连子记录一起删明细行,如"出价"
restrict有子记录时禁止删除主数据,如"类型"

不写 ondelete 时没有统一的默认值,Odoo 按 required 决定:必填字段默认 restrict,可选字段才默认 set null。必填字段显式写 set null 会直接 ValueError(ORM 不允许必填外键悬空)。

set null 需要注意:删掉一个类型,房源不会报错,只是类型变空,数据悄悄变脏。主数据表建议显式 restrict,明细行用 cascade。

10.2.4 x2many 字段必须用 Command ​

One2many / Many2many 的写入语义有五种,光给 id 无法表达"新增"还是"覆盖",所以 Odoo 用 Command 枚举(odoo.Command)明确意图:

写法含义
Command.set([id1, id2])全量替换为这两个(最常用)
Command.link(id)追加关联
Command.unlink(id)解除关联(不删记录)
Command.clear()清空
Command.create({...})顺带新建一条并关联
Command.delete(id)删除记录(慎用)

Command 从 odoo 顶层就能导入:from odoo import Command。

想在本模型上直接看到关联记录的字段,用 related:

python
property_type_id = fields.Many2one(
    related='property_id.type_id',
    string='房源类型',
    store=True,
)

如果不写 store=True 时它每次读取都实时穿透(不建列);写了就把值落库,查询快但需要维护依赖重算。

10.3 开发实践 ​

10.3.1 三个新模型 ​

models/estate_property_type.py:

python
from odoo import fields, models


class EstatePropertyType(models.Model):
    _name = 'estate.property.type'
    _description = '房源类型'
    _order = 'sequence, name'

    name = fields.Char(string='类型名称', required=True)
    sequence = fields.Integer(string='排序', default=10)
    property_ids = fields.One2many('estate.property', 'type_id', string='房源')

models/estate_property_tag.py 与 models/estate_property_offer.py(骨架):

python
class EstatePropertyTag(models.Model):
    _name = 'estate.property.tag'
    _description = '房源标签'

    name = fields.Char(string='标签', required=True)
    color = fields.Integer(string='颜色序号')


class EstatePropertyOffer(models.Model):
    _name = 'estate.property.offer'
    _description = '买家出价'

    price = fields.Float(string='出价', digits=(16, 2), required=True)
    partner_id = fields.Many2one('res.partner', string='买家', required=True)
    property_id = fields.Many2one('estate.property', string='房源',
                                  required=True, ondelete='cascade')
    property_type_id = fields.Many2one(related='property_id.type_id',
                                       string='房源类型', store=True)
    status = fields.Selection(
        selection=[('accepted', '已接受'), ('refused', '已拒绝')],
        string='状态', copy=False,
    )

10.3.2 在房源上挂关系 ​

python
type_id = fields.Many2one('estate.property.type', string='类型', ondelete='restrict')
tag_ids = fields.Many2many('estate.property.tag', string='标签')
offer_ids = fields.One2many('estate.property.offer', 'property_id', string='出价')

10.3.3 用 Command 写关系 ​

下面这段在 odoo-bin shell 里执行(tag_sea / buyer_a 等是已经存在的记录,shell 退出会回滚,写数据要自己 env.cr.commit()):

python
from odoo import Command

tag_sea, tag_new = env['estate.property.tag'].search([], limit=2)
buyer_a, buyer_b = env['res.partner'].search([], limit=2)

prop = env['estate.property'].create({
    'name': '滨海三居',
    'tag_ids': [Command.set([tag_sea.id, tag_new.id])],
    'offer_ids': [
        Command.create({'price': 480000, 'partner_id': buyer_a.id}),
        Command.create({'price': 500000, 'partner_id': buyer_b.id}),
    ],
})

# 后续只追加一个标签:不用把已有标签再写一遍
prop.write({'tag_ids': [Command.link(tag_view.id)]})

反过来,如果用了 [tag_sea.id, tag_new.id] 这样直接给 id,Odoo 会把它当成"要建新记录",报 ValueError: Invalid field ... 或写入脏数据。

10.3.4 配权限并验证 ​

三个新模型都要在 security/ir.access.csv 里补行,否则普通用户一进页面就 AccessError:

csv
access_estate_property_type,estate property type,estate.property.type,estate20.group_estate_agent,r,
access_estate_property_tag,estate property tag,estate.property.tag,estate20.group_estate_agent,crud,
access_estate_property_offer,estate property offer,estate.property.offer,estate20.group_estate_agent,crud,

执行下面的脚本验证:

shell
cd D:\odoo20
.\venv\Scripts\python.exe D:\workspace\winodoo\samples\ch10\estate20\test-script.py
;复制上面的 .py 代码

升级后验证三种关系的落库形态:

sql
-- 1. One2many 不建列:offer 表里有 property_id
SELECT column_name FROM information_schema.columns
WHERE table_name = 'estate_property_offer' AND column_name LIKE '%_id';

-- 2. Many2many 的中间表
SELECT to_regclass('public.estate_property_estate_property_tag_rel');

-- 3. 外键的删除策略:c = cascade, r = restrict, n = set null
SELECT conname, confdeltype FROM pg_constraint
WHERE conrelid = 'estate_property_offer'::regclass AND contype = 'f';

第 3 条应该能看到 property_id 是 c(因为我们写了 ondelete='cascade'),partner_id 是 r——它只写了 required=True、没写 ondelete,而必填的 Many2one 默认策略就是 restrict。想看到 n 可以顺手查一下房源表:estate_property_salesperson_id_fkey 是 n,因为 salesperson_id 是可空字段。

交给 AI(第 10 章 · 关系建模)

把下面这段发给任意 AI 对话(ChatGPT / Claude / Cursor 均可):

我们用的是 Odoo 20 社区版。已有模型 estate.property。请新增三个模型并挂上关系:

① estate.property.type(类型,含 sequence,反向 property_ids);② estate.property.tag(标签,含 color);③ estate.property.offer(出价,含 price / partner_id / property_id / status)。

要求:offers 用 ondelete='cascade',类型用 ondelete='restrict';在 offer 上加一个 related 到 property_id.type_id 并 store=True;给出用 Command 创建带标签与出价的房源的示例,并补三条 ir.access.csv 权限行。

10.4 总结 ​

验收清单
  • to_regclass('public.estate_property_estate_property_tag_rel') 返回表名
  • estate_property_offer 表里没有 offer_ids 列,只有 property_id 这类外键列
  • pg_constraint 里 property_id 的 confdeltype 为 c,partner_id 为 r(必填 m2o 的默认策略)
  • 删一条出价,房源还在;删一条房源,它的出价一起消失
  • 视图里能看到类型、标签、出价页签,且普通用户不报 AccessError

10.5 常见坑与排错 ​

现象原因处理
offer_ids 永远为空One2many 第二个参数写错字段名与对方的 Many2one 字段名逐字对齐
ValueError: Invalid field ...x2many 直接赋 id 列表用 Command.set(...) / Command.link(...)
删类型时房源的类型全变空ondelete 没写,可空字段默认置空主数据改 restrict
删房源报外键冲突子表 restrict 或必填 m2o 未写明细行改 cascade
中间表名对不上m2m 表名是两张表名排序后拼接用 \d estate_property_estate_property_tag_rel 确认
related 字段不更新少了 store=True 或依赖链没刷新加 store=True,或读实时值
普通用户打开新模型报 AccessError新模型没配权限补 ir.access.csv 行

参考与致谢:本章知识结构参考 Odoo 官方文档 Chapter 7: Relations between models (Odoo S.A.,CC BY-SA 4.0)。三种关系的落库对照、Command 语义表、外键策略验证 SQL 与排错表均为本站基于 Odoo 20 社区版独立编写并实测。 本站非 Odoo 官方站点,内容不代表 Odoo S.A. 观点。

最近更新