4
我有两组数据展现出一对一的关系。如何在Odoo 8中创建One2one关系?
我不能给两组数据合并的原因是:
- 特定记录可能只集合A中的存在,只是在集B,或两者在集A和集B;和
- 集合A和集合B中的记录之间的关联是暂时的,这意味着记录可以关联并且可以变为关联;和
- 集合A中的数据处理方式与集合B中的数据不同;和
- 有外部架构限制。
当集合A中的记录与集合B中的记录相关联时,我想链接这两个记录。当记录被链接时,关系必须是一对一的。 我如何保证这种关系是一对一的关系?
下面的代码看起来很接近,但我对Odoo的工作很陌生,并且不确定如何分析这种方法是否可以保证一对一的关系。
import openerp
class A(openerp.models.Model):
_name = 'set.a'
_sql_constraints = [
('set_b_id', 'unique("set_b_id")', 'Field set_b_id must be unique.'),
]
# Constrained to be unique (see SQL above) which essentially changes
# this end of the Many2one relationship to a One2one relationship. (The
# other end of the relationship must also be constrained.)
set_b_id = openerp.fields.Many2one(
comodel_name='set.b',
)
class B(openerp.models.Model):
_name = 'set.b'
# Constrained to tie with either zero keys or one key (see function
# below) which essentially changes this end of the One2many
# relationship to a One2one relationship. (The other end of the
# relationship must also be constrained.)
set_a_id = openerp.fields.One2many(
comodel_name='set.a',
inverse_name='set_b_id',
)
@openerp.api.constrains('set_a_id')
def _constrains_set_a_id(self):
if len(self.set_a_id) > 1:
raise openerp.exceptions.ValidationError('Additional linkage failed.')
另一种方法可能会延长openerp.fields重新创建之前已停用One2one关系,但我不能肯定可以做干净。