Inheritance and extension
Odoo提供了三种不同的机制来以模块化方式扩展模型:
- 从现有模型创建新模型,向副本添加新信息,但保留原始模块的原样
- 扩展其他模块中定义的模型,替换以前的版本
- 将一些模型的字段委托给它包含的记录
Classical inheritance(经典继承)
同时使用_inherit和_name属性时,Odoo使用现有的模型(通过_inherit提供)作为基础创建一个新模型。
新模型从其基础模型获取所有字段,方法和元信息(defaults & al)。
class Inheritance0(models.Model):
_name = 'inheritance.0'
_description = 'Inheritance Zero'
name = fields.Char()
def call(self):
return self.check("model 0")
def check(self, s):
return "This is {} record {}".format(s, self.name)
class Inheritance1(models.Model):
_name = 'inheritance.1'
_inherit = 'inheritance.0'
_description = 'Inheritance One'
def call(self):
return self.check("model 1")
当使用它们:
a = env['inheritance.0'].create({'name': 'A'})
b = env['inheritance.1'].create({'name': 'B'})
a.call()
b.call()
得到结果:
"This is model 0 record A"
"This is model 1 record B"
第二个模型继承自第一个模型的检查方法及其名称字段,但是重写了调用方法,就像使用标准的Python继承一样。
Extension(扩展)
当使用_inherit但不用_name时,新模型取代现有模型并进行扩展。这对于向现有模型添加新字段或方法(在其他模块中创建)非常有用,或者自定义或重新配置它们(例如,更改其默认排序顺序):
_name = 'extension.0'
_description = 'Extension zero'
name = fields.Char(default="A")
class Extension1(models.Model):
_inherit = 'extension.0'
description = fields.Char(default="Extended")
record = env['extension.0'].create({})
record.read()[0]
得到结果:
{'name': "A", 'description': "Extended"}
它也会产生各种 automatic fields ,除非它们被禁用。
Delegation(委托)
三种继承机制提供了更大的灵活性(可以在运行时更改)但修改更少。使用_inherits模型将当前模型中未找到的任何字段的查找委托给“子”模型。通过在父模型上自动设置的 Reference 字段执行委派:
class Child0(models.Model):
_name = 'delegation.child0'
_description = 'Delegation Child zero'
field_0 = fields.Integer()
class Child1(models.Model):
_name = 'delegation.child1'
_description = 'Delegation Child one'
field_1 = fields.Integer()
class Delegating(models.Model):
_name = 'delegation.parent'
_description = 'Delegation Parent'
_inherits = {
'delegation.child0': 'child0_id',
'delegation.child1': 'child1_id',
}
child0_id = fields.Many2one('delegation.child0', required=True, ondelete='cascade')
child1_id = fields.Many2one('delegation.child1', required=True, ondelete='cascade')
record = env['delegation.parent'].create({
'child0_id': env['delegation.child0'].create({'field_0': 0}).id,
'child1_id': env['delegation.child1'].create({'field_1': 1}).id,
})
record.field_0
record.field_1
结果如下:
0
1
并且可以直接在委托字段上书写:
record.write({'field_1': 4})
Warning!
使用委托继承时,方法不是继承的,只是字段