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_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