【发布时间】:2015-09-26 20:10:18
【问题描述】:
我有两组表现出一对一关系的数据。
我无法合并两组数据,因为:
- 特定记录可能仅存在于集合 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 关系,但我不确定这是否可以干净地完成。
【问题讨论】:
标签: postgresql odoo odoo-8 postgresql-9.4