diff --git a/oscar_odin/mappings/context.py b/oscar_odin/mappings/context.py index 397d411..0da1c5e 100644 --- a/oscar_odin/mappings/context.py +++ b/oscar_odin/mappings/context.py @@ -8,7 +8,7 @@ from oscar.core.loading import get_model from oscar.apps.catalogue.product_attributes import QuerysetCache -from ..utils import in_bulk +from ..utils import in_bulk, set_error_identifiers from ..exceptions import OscarOdinException from .constants import MODEL_IDENTIFIERS_MAPPING @@ -61,11 +61,15 @@ class ModelMapperContext(dict): instance_keys = None Model = None errors = None + delete_related = False + error_identifiers = None clean_instances = True update_related_models_same_type = True - def __init__(self, Model, *args, delete_related=False, **kwargs): + def __init__( + self, Model, *args, delete_related=False, error_identifiers=None, **kwargs + ): super().__init__(*args, **kwargs) self.foreign_key_items = defaultdict(list) self.many_to_many_items = defaultdict(list) @@ -76,6 +80,7 @@ def __init__(self, Model, *args, delete_related=False, **kwargs): self.attribute_data = [] self.errors = [] self.delete_related = delete_related + self.error_identifiers = error_identifiers self.Model = Model def __bool__(self): @@ -112,6 +117,9 @@ def validate_instances(self, instances, validate_unique=True, fields=None): validate_unique=validate_unique, exclude=exclude ) except ValidationError as e: + # Add details to identify the instance that produced this error + if self.error_identifiers: + set_error_identifiers(e, instance, self.error_identifiers) self.errors.append(e) else: validated_instances.append(instance) diff --git a/oscar_odin/utils.py b/oscar_odin/utils.py index b29b7f9..a3249c3 100644 --- a/oscar_odin/utils.py +++ b/oscar_odin/utils.py @@ -75,7 +75,18 @@ def querycounter(*labels, print_queries=False): print(" ", q) -def validate_resources(resources): +def set_error_identifiers(error, record, error_identifiers): + all_identifier_values = [] + for identifier in error_identifiers: + value = "" + if hasattr(record, identifier): + value = getattr(record, identifier) + all_identifier_values.append(str(value)) + error.identifier_values = all_identifier_values + return error + + +def validate_resources(resources, error_identifiers=None): errors = [] valid_resources = [] if not resources: @@ -90,5 +101,7 @@ def validate_resources(resources): resource.full_clean() valid_resources.append(resource) except ValidationError as error: + if error_identifiers is not None: + error = set_error_identifiers(error, resource, error_identifiers) errors.append(error) return valid_resources, errors