Odoo中model中使用_inherit / _inherits属性简介

6 篇文章 0 订阅
Odoo中model中使用_inherit / _inherits属性简介

以odoo12环境为例,生产厂家模型为例进行解释说明。


1.正常使用 “_inherit” 是用于对模型进行继承修改,常见于如下定义:

class AccountMove(models.Model):
    _inherit = 'account.move'

    stock_move_id = fields.Many2one('stock.move', string='Stock Move')

其中使用 “_inherit” 属性表示对原有模型的继承修改,这其中不包含 “_name” 属性。
查看数据库字段会发现对原有表增加新继承新定义的字段。


2.同时使用 “_inherit”“_name” 或者 同时使用 “_inherits”“_name” ,
2.1 先看 “_inherit”“_name” 同时存在情况,如下边代码定义:

class StockManufacturer(models.Model):
    _name = 'stock.manufacturer'
    _description = 'Stock Manufacturer'
    _order = 'id asc'

    # 名称
    name = fields.Char('Manufacturer Name', required=True, index=True)
    # 编码
    number = fields.Char('Manufacturer Number', index=True, copy=False)
    # 类型: 生产厂家、代理商
    manufacturer_type = fields.Selection([('manufacturer', 'Manufacturer'), ('agent', 'Agent')],
                                         string='Manufacturer Type', required=True)
    # 有效
    active = fields.Boolean('Active', default=True)
    # 说明
    instructions = fields.Char('Manufacturer Instructions')

    # 唯一性约束:检验生产厂家编码是否唯一
    _sql_constraints = [
        ('manufacturer_unique', 'unique (number)', _("Manufacturer Number already exists !")),
    ]


class StockManufacturerSon(models.Model):
    _name = 'stock.manufacturer.son'
    _inherit = 'stock.manufacturer'
    _description = 'Stock Manufacturer Son'
    _order = 'id asc'


    son = fields.Char('Son')

    daughter = fields.Char('Daughter')

可以看到同时使用 “_inherit”“_name” 属性,这个时候会生成两张表,分别为stock_manufacture、stock_manufacture_son。其中stock_manufacture_son会继承stock_manufacture中的字段,并增加自己模型中定义的字段。这种方式就类似与从stock_manufacture复制字段出来加上继承新增加字段,组成一张新表。
注意这个时候操作stock_manufacture_son是不会影响stock_manufacture表中的数据的。

数据库表截图如下:
stock_manufacture
stock_manufacture
stock_manufacture_son
在这里插入图片描述

2.2 先看 “_inherits”“_name” 同时存在情况,如下边代码定义:

class StockManufacturerSon(models.Model):
    _name = 'stock.manufacturer.grandson'
    _inherits = {'stock.manufacturer.son': 'grand_id'}
    _description = 'Stock Manufacturer Grand Son'
    _order = 'id asc'

    grandson = fields.Char('Son')

    granddaughter = fields.Char('Daughter')

这里注意 {‘stock.manufacturer.son’: ‘grand_id’},其中**'grand_id’字段作为stock_manufacturer_grandson表与stock_manufacturer_son的关联字段。这里的 “_inherits” 也类似与将两个模型字段结合形成新表的感觉,但是不同的是stock_manufacturer_grandson表不会存储stock_manufacturer_son表的字段,而是在odoo模型对象中可以直接通过对象点"."** 的方式直接访问stock.manufacturer.son对象的数据,其中stock.manufacturer.grandson对象直接操作stock.manufacturer.son对象数据,是会影响stock.manufacturer.son的对象数据的。

数据库表如下:

stock_manufacturer_grandson
在这里插入图片描述

  • 8
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值