I have two sets of data that exhibit a one-to-one relationship.
I am not able to merge the two sets of data because:
- Particular records may be present only in set A, only in set B, or both in set A and in set B; and
- The association between records in set A and in set B is transient, meaning records can become associated and can become disassociated; and
- The data in set A are processed differently than the data in set B; and
- There are external architectural constraints.
When a record in set A is associated with a record in set B, I want to link the two records. When records are linked, the relationship must be one-to-one. How do I guarantee that the relationship is a one-to-one relationship?
The following code seems close, but I am new to working with Odoo and am uncertain how to analyze whether or not this approach guarantees a one-to-one relationship.
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.')
Another approach might be to extend openerp.fields to recreate the previously deprecated One2one relationship, but I am not certain that could be done cleanly.