changeset d01f00e010c3 in trytond:default
details: https://hg.tryton.org/trytond?cmd=changeset&node=d01f00e010c3
description:
Use dictionary as domain for Reference field
issue11074
review383911002
diffstat:
CHANGELOG | 1 +
doc/ref/models/fields.rst | 5 ++
trytond/cache.py | 4 +-
trytond/model/fields/field.py | 4 +-
trytond/model/fields/reference.py | 17 +++++++-
trytond/model/modelstorage.py | 65 +++++++++++++++++++++-----------
trytond/tests/field_reference.py | 42 +++++++++++++++++++++
trytond/tests/test_cache.py | 4 +-
trytond/tests/test_field_reference.py | 70 ++++++++++++++++++++++++++++++++++-
9 files changed, 183 insertions(+), 29 deletions(-)
diffs (372 lines):
diff -r 2bbc59e018bc -r d01f00e010c3 CHANGELOG
--- a/CHANGELOG Thu Feb 03 22:24:34 2022 +0100
+++ b/CHANGELOG Thu Feb 03 23:05:47 2022 +0100
@@ -1,3 +1,4 @@
+* Use dictionary as domain on Reference field
* Include model, field and column in import data error message
* Support limit and offset to ModelSQL count search and search_count
* Apply view inheritance to board
diff -r 2bbc59e018bc -r d01f00e010c3 doc/ref/models/fields.rst
--- a/doc/ref/models/fields.rst Thu Feb 03 22:24:34 2022 +0100
+++ b/doc/ref/models/fields.rst Thu Feb 03 23:05:47 2022 +0100
@@ -55,6 +55,11 @@
A :ref:`domain <topics-domain>` constraint that will be applied on the field
value.
+.. note::
+
+ For :class:`Reference` field it is a dictionary that contains the domain per
+ model name.
+
``states``
----------
diff -r 2bbc59e018bc -r d01f00e010c3 trytond/cache.py
--- a/trytond/cache.py Thu Feb 03 22:24:34 2022 +0100
+++ b/trytond/cache.py Thu Feb 03 23:05:47 2022 +0100
@@ -45,7 +45,9 @@
def unfreeze(o):
- if isinstance(o, frozenset):
+ if isinstance(o, tuple):
+ return [unfreeze(x) for x in o]
+ elif isinstance(o, frozenset):
return dict((x, unfreeze(y)) for x, y in o)
else:
return o
diff -r 2bbc59e018bc -r d01f00e010c3 trytond/model/fields/field.py
--- a/trytond/model/fields/field.py Thu Feb 03 22:24:34 2022 +0100
+++ b/trytond/model/fields/field.py Thu Feb 03 23:05:47 2022 +0100
@@ -257,7 +257,7 @@
self.required = required
self.readonly = readonly
self.__domain = None
- self.domain = domain or []
+ self.domain = domain
self.__states = None
self.states = states or {}
self.select = bool(select)
@@ -302,6 +302,8 @@
return self.__domain
def _set_domain(self, value):
+ if value is None:
+ value = []
domain_validate(value)
self.__domain = value
diff -r 2bbc59e018bc -r d01f00e010c3 trytond/model/fields/reference.py
--- a/trytond/model/fields/reference.py Thu Feb 03 22:24:34 2022 +0100
+++ b/trytond/model/fields/reference.py Thu Feb 03 23:05:47 2022 +0100
@@ -11,8 +11,8 @@
from trytond.transaction import Transaction
from .field import (
- Field, context_validate, instantiate_context, search_order_validate,
- with_inactive_records)
+ Field, context_validate, domain_validate, instantiate_context,
+ search_order_validate, with_inactive_records)
from .selection import SelectionMixin
@@ -67,6 +67,19 @@
__init__.__doc__ += Field.__init__.__doc__
@property
+ def domain(self):
+ return self.__domain
+
+ @domain.setter
+ def domain(self, value):
+ if value is None:
+ value = {}
+ assert isinstance(value, dict)
+ for domain in value.values():
+ domain_validate(domain)
+ self.__domain = value
+
+ @property
def search_order(self):
return self.__search_order
diff -r 2bbc59e018bc -r d01f00e010c3 trytond/model/modelstorage.py
--- a/trytond/model/modelstorage.py Thu Feb 03 22:24:34 2022 +0100
+++ b/trytond/model/modelstorage.py Thu Feb 03 23:05:47 2022 +0100
@@ -10,7 +10,7 @@
from collections import defaultdict
from decimal import Decimal
from functools import lru_cache, wraps
-from itertools import chain, islice
+from itertools import chain, groupby, islice
from operator import itemgetter
from trytond.cache import Cache, LRUDictTransaction, freeze, unfreeze
@@ -1172,22 +1172,32 @@
def validate_domain(field):
if not field.domain:
return
- if field._type in ['dict', 'reference']:
+ if field._type == 'dict':
return
- if field._type in ('many2one', 'one2many'):
- Relation = pool.get(field.model_name)
- elif field._type in ('many2many', 'one2one'):
- Relation = field.get_target()
- else:
- Relation = cls
+
+ def get_relation(record):
+ if field._type in ('many2one', 'one2many'):
+ Relation = pool.get(field.model_name)
+ elif field._type in ('many2many', 'one2one'):
+ Relation = field.get_target()
+ elif field._type == 'reference':
+ value = getattr(record, field.name)
+ Relation = value.__class__ if value else None
+ else:
+ Relation = cls
+ return Relation
+
domains = defaultdict(lambda: defaultdict(list))
if is_pyson(field.domain) or is_pyson(field.context):
encoder = PYSONEncoder()
pyson_domain = encoder.encode(field.domain)
pyson_context = encoder.encode(field.context)
for record in records:
- domain = freeze(_record_eval_pyson(
- record, pyson_domain, encoded=True))
+ domain = _record_eval_pyson(
+ record, pyson_domain, encoded=True)
+ if isinstance(domain, dict):
+ domain = domain.get(get_relation(record).__name__, [])
+ domain = freeze(domain)
context = freeze(_record_eval_pyson(
record, pyson_context, encoded=True))
domains[context][domain].append(record)
@@ -1224,23 +1234,32 @@
records)
for context, ctx_domains in domains.items():
- for domain, sub_records in ctx_domains.items():
- with Transaction().set_context(unfreeze(context)):
- validate_relation_domain(
- field, sub_records, Relation, unfreeze(domain))
+ for domain, ctx_records in ctx_domains.items():
+ domain = unfreeze(domain)
+ for Relation, sub_records in groupby(
+ ctx_records, key=get_relation):
+ if not Relation:
+ continue
+ if isinstance(domain, dict):
+ sub_domain = domain.get(Relation.__name__)
+ if not sub_domain:
+ continue
+ else:
+ sub_domain = domain
+ with Transaction().set_context(unfreeze(context)):
+ validate_relation_domain(
+ field, list(sub_records), Relation, sub_domain)
def relation_domain(field, records):
- if field._type in ('many2one', 'one2many', 'many2many', 'one2one'):
- relations = set()
- for record in records:
- if getattr(record, field.name):
- if field._type in ('many2one', 'one2one'):
- relations.add(getattr(record, field.name))
- else:
- relations.update(getattr(record, field.name))
+ relations = set()
+ if field._type in {'many2one', 'one2one', 'reference'}:
+ relations.update(getattr(r, field.name) for r in records)
+ elif field._type in {'one2many', 'many2many'}:
+ relations.update(*(getattr(r, field.name) for r in records))
else:
# Cache alignment is not a problem
relations = set(records)
+ relations.discard(None)
return relations
def validate_relation_domain(field, records, Relation, domain):
@@ -1260,6 +1279,8 @@
domain = field.domain
if is_pyson(domain):
domain = _record_eval_pyson(records[0], domain)
+ if isinstance(domain, dict):
+ domain = domain.get(Relation.__class__, [])
msg = gettext(
'ir.msg_domain_validation_record',
**cls.__names__(field.name))
diff -r 2bbc59e018bc -r d01f00e010c3 trytond/tests/field_reference.py
--- a/trytond/tests/field_reference.py Thu Feb 03 22:24:34 2022 +0100
+++ b/trytond/tests/field_reference.py Thu Feb 03 23:05:47 2022 +0100
@@ -3,6 +3,7 @@
from trytond.model import ModelSQL, fields
from trytond.pool import Pool
+from trytond.pyson import Eval
from trytond.transaction import Transaction
@@ -49,6 +50,44 @@
return context.get('test')
+class ReferenceDomainValidation(ModelSQL):
+ "Reference Domain Validation"
+ __name__ = 'test.reference_domainvalidation'
+ reference = fields.Reference("Reference", selection=[
+ (None, ''),
+ ('test.reference.target', "Target"),
+ ('test.reference_domainvalidation.target', "Domain Target"),
+ ],
+ domain={
+ 'test.reference_domainvalidation.target': [
+ ('value', '>', 5),
+ ],
+ })
+
+
+class ReferenceDomainValidationTarget(ModelSQL):
+ "Reference Domain Validation Target"
+ __name__ = 'test.reference_domainvalidation.target'
+ value = fields.Integer("Value")
+
+
+class ReferenceDomainValidationPYSON(ModelSQL):
+ "Reference Domain Validation"
+ __name__ = 'test.reference_domainvalidation_pyson'
+ reference = fields.Reference("Reference", selection=[
+ (None, ''),
+ ('test.reference.target', "Target"),
+ ('test.reference_domainvalidation.target', "Domain Target"),
+ ],
+ domain={
+ 'test.reference_domainvalidation.target': [
+ ('value', '>', Eval('value')),
+ ],
+ },
+ depends=['value'])
+ value = fields.Integer("Value")
+
+
def register(module):
Pool.register(
Reference,
@@ -56,4 +95,7 @@
ReferenceRequired,
ReferenceContext,
ReferenceContextTarget,
+ ReferenceDomainValidation,
+ ReferenceDomainValidationTarget,
+ ReferenceDomainValidationPYSON,
module=module, type_='model')
diff -r 2bbc59e018bc -r d01f00e010c3 trytond/tests/test_cache.py
--- a/trytond/tests/test_cache.py Thu Feb 03 22:24:34 2022 +0100
+++ b/trytond/tests/test_cache.py Thu Feb 03 23:05:47 2022 +0100
@@ -44,7 +44,7 @@
def testUnfreeze(self):
"Test unfreeze"
for value, result in [
- (freeze([1, 2, 3]), (1, 2, 3)),
+ (freeze([1, 2, 3]), [1, 2, 3]),
(freeze({'dict': {
'inner dict': {
'list': [1, 2, 3],
@@ -54,7 +54,7 @@
}),
{'dict': {
'inner dict': {
- 'list': (1, 2, 3),
+ 'list': [1, 2, 3],
'string': 'test',
},
},
diff -r 2bbc59e018bc -r d01f00e010c3 trytond/tests/test_field_reference.py
--- a/trytond/tests/test_field_reference.py Thu Feb 03 22:24:34 2022 +0100
+++ b/trytond/tests/test_field_reference.py Thu Feb 03 23:05:47 2022 +0100
@@ -2,7 +2,8 @@
# this repository contains the full copyright notices and license terms.
import unittest
-from trytond.model.exceptions import RequiredValidationError
+from trytond.model.exceptions import (
+ DomainValidationError, RequiredValidationError)
from trytond.pool import Pool
from trytond.tests.test_tryton import activate_module, with_transaction
@@ -457,6 +458,73 @@
self.assertEqual(record.target.context, 'foo')
+ @with_transaction()
+ def test_domain_valid(self):
+ "Test reference with valid domain"
+ pool = Pool()
+ Reference = pool.get('test.reference_domainvalidation')
+ Target = pool.get('test.reference_domainvalidation.target')
+ target = Target(value=42)
+ target.save()
+
+ reference, = Reference.create([{
+ 'reference': str(target),
+ }])
+ self.assertEqual(reference.reference, target)
+
+ @with_transaction()
+ def test_domain_invalid(self):
+ "Test reference with invalid domain"
+ pool = Pool()
+ Reference = pool.get('test.reference_domainvalidation')
+ Target = pool.get('test.reference_domainvalidation.target')
+ target = Target(value=1)
+ target.save()
+
+ reference = Reference(reference=target)
+ with self.assertRaises(DomainValidationError):
+ reference.save()
+
+ @with_transaction()
+ def test_no_domain(self):
+ "Test reference with no domain"
+ pool = Pool()
+ Reference = pool.get('test.reference_domainvalidation')
+ Target = pool.get('test.reference.target')
+ target = Target(name="Test")
+ target.save()
+
+ reference, = Reference.create([{
+ 'reference': str(target),
+ }])
+ self.assertEqual(reference.reference, target)
+
+ @with_transaction()
+ def test_domain_none_value(self):
+ "Test reference with domain and None value"
+ pool = Pool()
+ Reference = pool.get('test.reference_domainvalidation')
+
+ reference, = Reference.create([{
+ 'reference': None,
+ }])
+ self.assertEqual(reference.reference, None)
+
+ @with_transaction()
+ def test_domain_pyson(self):
+ "Test reference with pyson domain"
+ pool = Pool()
+ Reference = pool.get('test.reference_domainvalidation_pyson')
+ Target = pool.get('test.reference_domainvalidation.target')
+ target = Target(value=42)
+ target.save()
+
+ reference, = Reference.create([{
+ 'value': 1,
+ 'reference': str(target),
+ }])
+ self.assertEqual(reference.reference, target)
+
def suite():
return unittest.TestLoader().loadTestsFromTestCase(FieldReferenceTestCase)