[IMP] fields: relational fields automatically behave as mapped

In other words, `recs.foo_id == recs.mapped('foo_id')`.
This commit is contained in:
Raphael Collet
2019-04-30 07:54:49 +00:00
parent 0d21735a92
commit 63bc6013ab
2 changed files with 17 additions and 2 deletions
+7 -1
View File
@@ -491,11 +491,13 @@ class TestAPI(common.TransactionCase):
""" Check map on recordsets. """
ps = self.env['res.partner'].search([])
parents = ps.browse()
for p in ps: parents |= p.parent_id
for p in ps:
parents |= p.parent_id
# map a single field
self.assertEqual(ps.mapped(lambda p: p.parent_id), parents)
self.assertEqual(ps.mapped('parent_id'), parents)
self.assertEqual(ps.parent_id, parents)
# map a sequence of fields
self.assertEqual(
@@ -506,6 +508,10 @@ class TestAPI(common.TransactionCase):
ps.mapped('parent_id.name'),
[p.name for p in parents]
)
self.assertEqual(
ps.parent_id.mapped('name'),
[p.name for p in parents]
)
# map an empty sequence of fields
self.assertEqual(ps.mapped(''), ps)
+10 -1
View File
@@ -989,7 +989,7 @@ class Field(MetaField('DummyField', (object,), {})):
if record is None:
return self # the field is accessed through the owner class
if record:
if record._ids:
# only a single record may be accessed
record.ensure_one()
try:
@@ -2033,6 +2033,15 @@ class _Relational(Field):
'context': {}, # context for searching values
}
def __get__(self, records, owner):
# base case: do the regular access
if records is None or len(records._ids) <= 1:
return super().__get__(records, owner)
# multirecord case: return the union of the values of 'self' on records
get = super().__get__
comodel = records.env[self.comodel_name]
return comodel.union(*[get(record, owner) for record in records])
def _setup_regular_base(self, model):
super(_Relational, self)._setup_regular_base(model)
if self.comodel_name not in model.pool: