参考链接
https://www.odoo.com/documentation/10.0/howtos/backend.html#relations-between-models
https://www.odoo.com/documentation/10.0/howtos/backend.html#inheritance
模型关联
-
odoo的模型关联初步来看和数据库表关联一样,分为三种关联方式:多对多,多对一,一对多,这三种方式的关联与数据库通过外键建表最后的成果是一样的。只不过odoo将一些数据库的sql操作,封装成了fields的方法。
-
Many2one(comodel_name=<object object>, string=<object object>, **kwargs)
Many2one
多对一关系,在models文件中通过fields.Many2one声明
project_id = fields.Many2one('demo.project', ondelete='cascade', string=u'所属项目')
声明的结果是:会在数据库声明的表单中增加一个字段,字段名就是上句中的变量名
-
One2many(comodel_name=<object object>, inverse_name=<object object>, string=<object object>, kwargs)
一对多关系,是一个虚拟的表关系,依赖于Many2one,通过fields.One2many声明。注意:该关系需要many-表中已经声明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)
多对多关系,通过fields.Many2many声明。
user_ids = fields.Many2many('res.partner', string='Attendees')
声明的结果是,数据库会生成一个表单,维护两个表的map id
模型继承
模型继承- 模型扩展继承
在原模型对象基础上,继承原模型的属性,可以添加元素。不能修改原元素。
在数据库中,新模型对象增加的字段,实际是在原模型对象的数据库表单中添加的字段,没有新建表单。(兼容原模型,因为表单并没有改变)
class Extension0(models.Model):
_name = 'extension.0'
name = fields.Char(default="A")
class Extension1(models.Model):
_inherit = 'extension.0'
description = fields.Char(default="Extended")
- 经典继承
在原模型对象的基础上,继承原模型的属性,可以增加,重写原元素。
在数据库中,新建表单,复制了原模型对象的表单属性。和类的继承差不多。
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继承多个对象
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
网友评论