feat(import_export): explicite les erreurs lorsque la FK n'existe pas
Parent
697b215243
révision
e7ffdd02a4
|
@ -7,19 +7,11 @@ from ..references.models import (
|
|||
FormeJuridique,
|
||||
StatutStructure,
|
||||
)
|
||||
from ..resources_mixin import FkExplicitError, UserMixin
|
||||
from .models import Personne, Structure
|
||||
|
||||
|
||||
class UserMixin:
|
||||
def after_import_instance(self, instance, new, **kwargs):
|
||||
if instance.utilisateur_derniere_modification_id is None:
|
||||
user = kwargs.get('user')
|
||||
user = user and user.id
|
||||
instance.utilisateur_derniere_modification_id = user
|
||||
super().after_import_instance(instance, new, **kwargs)
|
||||
|
||||
|
||||
class StructureResource(UserMixin, resources.ModelResource):
|
||||
class StructureResource(UserMixin, FkExplicitError, resources.ModelResource):
|
||||
class Meta:
|
||||
model = Structure
|
||||
clean_model_instances = True
|
||||
|
|
|
@ -0,0 +1,41 @@
|
|||
from django.core.exceptions import (
|
||||
MultipleObjectsReturned,
|
||||
ObjectDoesNotExist,
|
||||
ValidationError,
|
||||
)
|
||||
|
||||
|
||||
class UserMixin:
|
||||
def after_import_instance(self, instance, new, **kwargs):
|
||||
if instance.utilisateur_derniere_modification_id is None:
|
||||
user = kwargs.get('user')
|
||||
user = user and user.id
|
||||
instance.utilisateur_derniere_modification_id = user
|
||||
super().after_import_instance(instance, new, **kwargs)
|
||||
|
||||
|
||||
class FkExplicitError:
|
||||
def import_obj(self, obj, data, dry_run):
|
||||
"inject error flag in instance"
|
||||
obj._error_flag = False
|
||||
try:
|
||||
super().import_obj(obj, data, dry_run)
|
||||
except ValidationError as err:
|
||||
obj._error_flag = True
|
||||
raise (err)
|
||||
|
||||
def skip_row(self, instance, original):
|
||||
"does not skip row if there is an error flag"
|
||||
if instance._error_flag:
|
||||
return False
|
||||
return super().skip_row(instance, original)
|
||||
|
||||
def import_field(self, field, obj, data, is_m2m=False):
|
||||
"convert DoesNotExist or MultipleObjectsReturn into ValueError"
|
||||
try:
|
||||
super().import_field(field, obj, data, is_m2m)
|
||||
except (ObjectDoesNotExist, MultipleObjectsReturned) as err:
|
||||
if isinstance(err, ObjectDoesNotExist):
|
||||
raise ValueError('non trouvé(e)')
|
||||
else:
|
||||
raise ValueError('non unique')
|
Chargement…
Référencer dans un nouveau ticket