參考鏈接
https://www.odoo.com/documentation/10.0/howtos/backend.html#relations-between-models
https://www.odoo.com/documentation/10.0/howtos/backend.html#inheritance
模型關(guān)聯(lián)
odoo的模型關(guān)聯(lián)初步來看和數(shù)據(jù)庫表關(guān)聯(lián)一樣,分為三種關(guān)聯(lián)方式:多對多,多對一根欧,一對多疾忍,這三種方式的關(guān)聯(lián)與數(shù)據(jù)庫通過外鍵建表最后的成果是一樣的。只不過odoo將一些數(shù)據(jù)庫的sql操作横媚,封裝成了fields的方法纠炮。
-
Many2one(comodel_name=<object object>, string=<object object>, **kwargs)
多對一關(guān)系,在models文件中通過fields.Many2one聲明
project_id = fields.Many2one('demo.project', ondelete='cascade', string=u'所屬項(xiàng)目')
聲明的結(jié)果是:會(huì)在數(shù)據(jù)庫聲明的表單中增加一個(gè)字段灯蝴,字段名就是上句中的變量名
One2many(comodel_name=<object object>, inverse_name=<object object>, string=<object object>, kwargs)
一對多關(guān)系恢口,是一個(gè)虛擬的表關(guān)系,依賴于Many2one穷躁,通過fields.One2many聲明耕肩。注意:該關(guān)系需要many-表中已經(jīng)聲明Many2one,否則失效inverse_name為many表中Many2one的字段名
attachment_ids = fields.One2many('demo.attachment', 'project_id', string=u'附件列表')
Many2many(comodel_name=<object object>, relation=<object object>, column1=<object object>, column2=<object object>, string=<object object>, **kwargs)
多對多關(guān)系问潭,通過fields.Many2many聲明猿诸。
user_ids = fields.Many2many('res.partner', string='Attendees')
聲明的結(jié)果是,數(shù)據(jù)庫會(huì)生成一個(gè)表單狡忙,維護(hù)兩個(gè)表的map id
模型繼承
- 模型擴(kuò)展繼承
在原模型對象基礎(chǔ)上梳虽,繼承原模型的屬性,可以添加元素灾茁。不能修改原元素窜觉。
在數(shù)據(jù)庫中,新模型對象增加的字段北专,實(shí)際是在原模型對象的數(shù)據(jù)庫表單中添加的字段禀挫,沒有新建表單。(兼容原模型逗余,因?yàn)楸韱尾]有改變)
class Extension0(models.Model):
_name = 'extension.0'
name = fields.Char(default="A")
class Extension1(models.Model):
_inherit = 'extension.0'
description = fields.Char(default="Extended")
- 經(jīng)典繼承
在原模型對象的基礎(chǔ)上特咆,繼承原模型的屬性,可以增加录粱,重寫原元素腻格。
在數(shù)據(jù)庫中,新建表單啥繁,復(fù)制了原模型對象的表單屬性菜职。和類的繼承差不多。
class Inheritance0(models.Model):
_name = 'inheritance.0'
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'
def call(self):
return self.check("model 1")
- 委托繼承
支持多重繼承旗闽,通過list繼承多個(gè)對象
class Child0(models.Model):
_name = 'delegation.child0'
field_0 = fields.Integer()
class Child1(models.Model):
_name = 'delegation.child1'
field_1 = fields.Integer()
class Delegating(models.Model):
_name = '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')
使用
super(TestDelegation, self).setUp()
env = self.env
record = env['delegation.parent'].create({
'child0_id': env['delegation.child0'].create({'field_0': 0}).id,
# children fields can be looked up on the parent record directly
env = self.env
record.field_0
record.field_1