1. 程式人生 > >Odoo12 ORM API ☞ Inheritance and extension

Odoo12 ORM API ☞ Inheritance and extension

Inheritance and extension


Odoo提供了三種不同的機制來以模組化方式擴充套件模型:

  • 從現有模型建立新模型,向副本新增新資訊,但保留原始模組的原樣
  • 擴充套件其他模組中定義的模型,替換以前的版本
  • 將一些模型的欄位委託給它包含的記錄

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!
使用委託繼承時,方法不是繼承的,只是欄位