-
-
Notifications
You must be signed in to change notification settings - Fork 782
/
resources.py
1310 lines (1091 loc) · 45.8 KB
/
resources.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import functools
import logging
import traceback
from collections import OrderedDict
from copy import deepcopy
from html import escape
from warnings import warn
import tablib
from diff_match_patch import diff_match_patch
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured, ValidationError
from django.core.management.color import no_style
from django.core.paginator import Paginator
from django.db import connections, router
from django.db.models import fields
from django.db.models.fields.related import ForeignKey
from django.db.models.query import QuerySet
from django.db.transaction import TransactionManagementError, set_rollback
from django.utils.encoding import force_str
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _
from . import widgets
from .declarative import DeclarativeMetaclass, ModelDeclarativeMetaclass
from .exceptions import FieldError
from .fields import Field
from .results import Error, Result, RowResult
from .utils import atomic_if_using_transaction, get_related_model
logger = logging.getLogger(__name__)
# Set default logging handler to avoid "No handler found" warnings.
logger.addHandler(logging.NullHandler())
def has_natural_foreign_key(model):
"""
Determine if a model has natural foreign key functions
"""
return hasattr(model, "natural_key") and hasattr(
model.objects, "get_by_natural_key"
)
class Diff:
def __init__(self, resource, instance, new):
self.left = Diff._read_field_values(resource, instance)
self.right = []
self.new = new
def compare_with(self, resource, instance):
self.right = Diff._read_field_values(resource, instance)
def as_html(self):
data = []
dmp = diff_match_patch()
for v1, v2 in zip(self.left, self.right):
if v1 != v2 and self.new:
v1 = ""
diff = dmp.diff_main(force_str(v1), force_str(v2))
dmp.diff_cleanupSemantic(diff)
html = dmp.diff_prettyHtml(diff)
html = mark_safe(html)
data.append(html)
return data
@classmethod
def _read_field_values(cls, resource, instance):
return [f.export(instance) for f in resource.get_import_fields()]
class Resource(metaclass=DeclarativeMetaclass):
"""
Resource defines how objects are mapped to their import and export
representations and handle importing and exporting data.
"""
def __init__(self, **kwargs):
"""
kwargs:
An optional dict of kwargs.
Subclasses can use kwargs to pass dynamic values to enhance import / exports.
"""
# The fields class attribute is the *class-wide* definition of
# fields. Because a particular *instance* of the class might want to
# alter self.fields, we create self.fields here by copying cls.fields.
# Instances should always modify self.fields; they should not modify
# cls.fields.
self.fields = deepcopy(self.fields)
# lists to hold model instances in memory when bulk operations are enabled
self.create_instances = list()
self.update_instances = list()
self.delete_instances = list()
@classmethod
def get_result_class(self):
"""
Returns the class used to store the result of an import.
"""
return Result
@classmethod
def get_row_result_class(self):
"""
Returns the class used to store the result of a row import.
"""
return RowResult
@classmethod
def get_error_result_class(self):
"""
Returns the class used to store an error resulting from an import.
"""
return Error
@classmethod
def get_diff_class(self):
"""
Returns the class used to display the diff for an imported instance.
"""
return Diff
@classmethod
def get_db_connection_name(self):
if self._meta.using_db is None:
return router.db_for_write(self._meta.model)
else:
return self._meta.using_db
def get_use_transactions(self):
if self._meta.use_transactions is None:
return getattr(settings, "IMPORT_EXPORT_USE_TRANSACTIONS", True)
else:
return self._meta.use_transactions
def get_chunk_size(self):
if self._meta.chunk_size is None:
return getattr(settings, "IMPORT_EXPORT_CHUNK_SIZE", 100)
else:
return self._meta.chunk_size
def get_fields(self, **kwargs):
"""
Returns list of fields (unordered).
"""
return list(self.fields.values())
def get_field_name(self, field):
"""
Returns the field name for a given field.
"""
for field_name, f in self.fields.items():
if f == field:
return field_name
raise AttributeError(
"Field %s does not exists in %s resource" % (field, self.__class__)
)
def init_instance(self, row=None):
"""
Initializes an object. Implemented in
:meth:`import_export.resources.ModelResource.init_instance`.
"""
raise NotImplementedError()
def get_instance(self, instance_loader, row):
"""
Calls the :doc:`InstanceLoader <api_instance_loaders>`.
"""
return instance_loader.get_instance(row)
def get_or_init_instance(self, instance_loader, row):
"""
Either fetches an already existing instance or initializes a new one.
"""
if not self._meta.force_init_instance:
instance = self.get_instance(instance_loader, row)
if instance:
return instance, False
return self.init_instance(row), True
def get_import_id_fields(self):
""" """
return self._meta.import_id_fields
def get_bulk_update_fields(self):
"""
Returns the fields to be included in calls to bulk_update().
``import_id_fields`` are removed because `id` fields cannot be supplied to
bulk_update().
"""
return [f for f in self.fields if f not in self._meta.import_id_fields]
def bulk_create(
self, using_transactions, dry_run, raise_errors, batch_size=None, result=None
):
"""
Creates objects by calling ``bulk_create``.
"""
try:
if len(self.create_instances) > 0:
if not using_transactions and dry_run:
pass
else:
self._meta.model.objects.bulk_create(
self.create_instances, batch_size=batch_size
)
except Exception as e:
self.handle_import_error(result, e, raise_errors)
finally:
self.create_instances.clear()
def bulk_update(
self, using_transactions, dry_run, raise_errors, batch_size=None, result=None
):
"""
Updates objects by calling ``bulk_update``.
"""
try:
if len(self.update_instances) > 0:
if not using_transactions and dry_run:
pass
else:
self._meta.model.objects.bulk_update(
self.update_instances,
self.get_bulk_update_fields(),
batch_size=batch_size,
)
except Exception as e:
self.handle_import_error(result, e, raise_errors)
finally:
self.update_instances.clear()
def bulk_delete(self, using_transactions, dry_run, raise_errors, result=None):
"""
Deletes objects by filtering on a list of instances to be deleted,
then calling ``delete()`` on the entire queryset.
"""
try:
if len(self.delete_instances) > 0:
if not using_transactions and dry_run:
pass
else:
delete_ids = [o.pk for o in self.delete_instances]
self._meta.model.objects.filter(pk__in=delete_ids).delete()
except Exception as e:
self.handle_import_error(result, e, raise_errors)
finally:
self.delete_instances.clear()
def validate_instance(
self, instance, import_validation_errors=None, validate_unique=True
):
"""
Takes any validation errors that were raised by
:meth:`~import_export.resources.Resource.import_instance`, and combines them
with validation errors raised by the instance's ``full_clean()``
method. The combined errors are then re-raised as single, multi-field
ValidationError.
If the ``clean_model_instances`` option is False, the instances's
``full_clean()`` method is not called, and only the errors raised by
``import_instance()`` are re-raised.
"""
if import_validation_errors is None:
errors = {}
else:
errors = import_validation_errors.copy()
if self._meta.clean_model_instances:
try:
instance.full_clean(
exclude=errors.keys(),
validate_unique=validate_unique,
)
except ValidationError as e:
errors = e.update_error_dict(errors)
if errors:
raise ValidationError(errors)
def save_instance(self, instance, is_create, row, **kwargs):
r"""
Takes care of saving the object to the database.
Objects can be created in bulk if ``use_bulk`` is enabled.
:param instance: The instance of the object to be persisted.
:param is_create: A boolean flag to indicate whether this is a new object
to be created, or an existing object to be updated.
:param row: A dict representing the import row.
:param \**kwargs:
See :meth:`import_row
"""
self.before_save_instance(instance, row, **kwargs)
if self._meta.use_bulk:
if is_create:
self.create_instances.append(instance)
else:
self.update_instances.append(instance)
else:
if not self._is_using_transactions(kwargs) and self._is_dry_run(kwargs):
# we don't have transactions and we want to do a dry_run
pass
else:
self.do_instance_save(instance)
self.after_save_instance(instance, row, **kwargs)
def do_instance_save(self, instance):
"""
A method specifically to provide a single overridable hook for the instance
save operation.
For example, this can be overridden to implement update_or_create().
:param instance: The model instance to be saved.
"""
instance.save()
def before_save_instance(self, instance, row, **kwargs):
r"""
Override to add additional logic. Does nothing by default.
:param instance: A new or existing model instance.
:param row: A ``dict`` containing key / value data for the row to be imported.
:param \**kwargs:
See :meth:`import_row`
"""
pass
def after_save_instance(self, instance, row, **kwargs):
r"""
Override to add additional logic. Does nothing by default.
:param instance: A new or existing model instance.
:param row: A ``dict`` containing key / value data for the row to be imported.
:param \**kwargs:
See :meth:`import_row`
"""
pass
def delete_instance(self, instance, row, **kwargs):
r"""
Calls :meth:`instance.delete` as long as ``dry_run`` is not set.
If ``use_bulk`` then instances are appended to a list for bulk import.
:param instance: A new or existing model instance.
:param row: A ``dict`` containing key / value data for the row to be imported.
:param \**kwargs:
See :meth:`import_row`
"""
self.before_delete_instance(instance, row, **kwargs)
if self._meta.use_bulk:
self.delete_instances.append(instance)
else:
if not self._is_using_transactions(kwargs) and self._is_dry_run(kwargs):
# we don't have transactions and we want to do a dry_run
pass
else:
instance.delete()
self.after_delete_instance(instance, row, **kwargs)
def before_delete_instance(self, instance, row, **kwargs):
r"""
Override to add additional logic. Does nothing by default.
:param instance: A new or existing model instance.
:param row: A ``dict`` containing key / value data for the row to be imported.
:param \**kwargs:
See :meth:`import_row`
"""
pass
def after_delete_instance(self, instance, row, **kwargs):
r"""
Override to add additional logic. Does nothing by default.
:param instance: A new or existing model instance.
:param row: A ``dict`` containing key / value data for the row to be imported.
:param \**kwargs:
See :meth:`import_row`
"""
pass
def import_field(self, field, instance, row, is_m2m=False, **kwargs):
r"""
Handles persistence of the field data.
:param field: A :class:`import_export.fields.Field` instance.
:param instance: A new or existing model instance.
:param row: A ``dict`` containing key / value data for the row to be imported.
:param is_m2m: A boolean value indicating whether or not this is a
many-to-many field.
:param \**kwargs:
See :meth:`import_row`
"""
if not field.attribute:
logger.debug(f"skipping field '{field}' - field attribute is not defined")
return
if field.column_name not in row:
logger.debug(
f"skipping field '{field}' "
f"- column name '{field.column_name}' is not present in row"
)
return
field.save(instance, row, is_m2m, **kwargs)
def get_import_fields(self):
return [self.fields[f] for f in self.get_import_order()]
def import_obj(self, obj, data, dry_run, **kwargs):
warn(
"The 'import_obj' method is deprecated and will be replaced "
"with 'import_instance(self, instance, row, **kwargs)' "
"in a future release. Refer to Release Notes for details.",
DeprecationWarning,
stacklevel=2,
)
if dry_run is True:
kwargs.update({"dry_run": dry_run})
self.import_instance(obj, data, **kwargs)
def import_instance(self, instance, row, **kwargs):
r"""
Traverses every field in this Resource and calls
:meth:`~import_export.resources.Resource.import_field`. If
``import_field()`` results in a ``ValueError`` being raised for
one of more fields, those errors are captured and reraised as a single,
multi-field ValidationError.
:param instance: A new or existing model instance.
:param row: A ``dict`` containing key / value data for the row to be imported.
:param \**kwargs:
See :meth:`import_row`
"""
errors = {}
for field in self.get_import_fields():
if isinstance(field.widget, widgets.ManyToManyWidget):
continue
try:
self.import_field(field, instance, row, **kwargs)
except ValueError as e:
errors[field.attribute] = ValidationError(force_str(e), code="invalid")
if errors:
raise ValidationError(errors)
def save_m2m(self, instance, row, **kwargs):
r"""
Saves m2m fields.
Model instance need to have a primary key value before
a many-to-many relationship can be used.
:param instance: A new or existing model instance.
:param row: A ``dict`` containing key / value data for the row to be imported.
:param \**kwargs:
See :meth:`import_row`
"""
using_transactions = self._is_using_transactions(kwargs)
dry_run = self._is_dry_run(kwargs)
if (not using_transactions and dry_run) or self._meta.use_bulk:
# we don't have transactions and we want to do a dry_run
# OR use_bulk is enabled (m2m operations are not supported
# for bulk operations)
pass
else:
for field in self.get_import_fields():
if not isinstance(field.widget, widgets.ManyToManyWidget):
continue
self.import_field(field, instance, row, True)
def for_delete(self, row, instance):
"""
Returns ``True`` if ``row`` importing should delete instance.
Default implementation returns ``False``.
Override this method to handle deletion.
:param row: A ``dict`` containing key / value data for the row to be imported.
:param instance: A new or existing model instance.
"""
return False
def skip_row(self, instance, original, row, import_validation_errors=None):
"""
Returns ``True`` if ``row`` importing should be skipped.
Default implementation returns ``False`` unless skip_unchanged == True
and skip_diff == False.
If skip_diff is True, then no comparisons can be made because ``original``
will be None.
When left unspecified, skip_diff and skip_unchanged both default to ``False``,
and rows are never skipped.
By default, rows are not skipped if validation errors have been detected
during import. You can change this behavior and choose to ignore validation
errors by overriding this method.
Override this method to handle skipping rows meeting certain
conditions.
Use ``super`` if you want to preserve default handling while overriding
::
class YourResource(ModelResource):
def skip_row(self, instance, original, row, import_validation_errors=None):
# Add code here
return super().skip_row(instance, original, row,
import_validation_errors=import_validation_errors)
:param instance: A new or updated model instance.
:param original: The original persisted model instance.
:param row: A ``dict`` containing key / value data for the row to be imported.
:param import_validation_errors: A ``dict`` containing key / value data for any
identified validation errors.
"""
if (
not self._meta.skip_unchanged
or self._meta.skip_diff
or import_validation_errors
):
return False
for field in self.get_import_fields():
# For fields that are models.fields.related.ManyRelatedManager
# we need to compare the results
if isinstance(field.widget, widgets.ManyToManyWidget):
# #1437 - handle m2m field not present in import file
if field.column_name not in row.keys():
continue
# m2m instance values are taken from the 'row' because they
# have not been written to the 'instance' at this point
instance_values = list(field.clean(row))
original_values = (
list()
if original.pk is None
else list(field.get_value(original).all())
)
if len(instance_values) != len(original_values):
return False
if sorted(v.pk for v in instance_values) != sorted(
v.pk for v in original_values
):
return False
else:
if field.get_value(instance) != field.get_value(original):
return False
return True
def get_diff_headers(self):
"""
Diff representation headers.
"""
return self.get_user_visible_headers()
def before_import(self, dataset, **kwargs):
r"""
Override to add additional logic. Does nothing by default.
:param dataset: A ``tablib.Dataset``.
:param \**kwargs:
See :meth:`import_row`
"""
pass
def after_import(self, dataset, result, **kwargs):
r"""
Override to add additional logic. Does nothing by default.
:param dataset: A ``tablib.Dataset``.
:param result: A :class:`import_export.results.Result` implementation
containing a summary of the import.
:param \**kwargs:
See :meth:`import_row`
"""
pass
def before_import_row(self, row, **kwargs):
r"""
Override to add additional logic. Does nothing by default.
:param row: A ``dict`` containing key / value data for the row to be imported.
:param \**kwargs:
See :meth:`import_row`
"""
pass
def after_import_row(self, row, row_result, **kwargs):
r"""
Override to add additional logic. Does nothing by default.
:param row: A ``dict`` containing key / value data for the row to be imported.
:param row_result: A ``RowResult`` instance.
References the persisted ``instance`` as an attribute.
:param \**kwargs:
See :meth:`import_row`
"""
pass
def after_import_instance(self, instance, new, row_number=None, **kwargs):
warn(
"The 'after_import_instance' method is deprecated and will be replaced "
"with 'after_init_instance(self, instance, new, row, **kwargs)' "
"in a future release. Refer to Release Notes for details.",
DeprecationWarning,
stacklevel=2,
)
if row_number is not None:
kwargs.update({"row_number": row_number})
self.after_init_instance(instance, new, None, **kwargs)
def after_init_instance(self, instance, new, row, **kwargs):
r"""
Override to add additional logic. Does nothing by default.
:param instance: A new or existing model instance.
:param new: a boolean flag indicating whether instance is new or existing.
:param row: A ``dict`` containing key / value data for the row to be imported.
:param \**kwargs:
See :meth:`import_row`
"""
pass
def handle_import_error(self, result, error, raise_errors=False):
logger.debug(error, exc_info=error)
if result:
tb_info = traceback.format_exc()
result.append_base_error(self.get_error_result_class()(error, tb_info))
if raise_errors:
raise
def import_row(self, row, instance_loader, **kwargs):
r"""
Imports data from ``tablib.Dataset``. Refer to :doc:`import_workflow`
for a more complete description of the whole import process.
:param row: A ``dict`` of the 'row' to import.
A row is a dict of data fields so can be a csv line, a JSON object,
a YAML object etc.
:param instance_loader: The instance loader to be used to load the model
instance associated with the row (if there is one).
:param \**kwargs:
See below.
:Keyword Arguments:
* dry_run (``boolean``) --
A True value means that no data should be persisted.
* use_transactions (``boolean``) --
A True value means that transactions will be rolled back.
* row_number (``int``) --
The index of the row being imported.
"""
skip_diff = self._meta.skip_diff
if not self._meta.store_instance:
self._meta.store_instance = kwargs.get(
"retain_instance_in_row_result", False
)
row_result = self.get_row_result_class()()
if self._meta.store_row_values:
row_result.row_values = row
original = None
try:
self.before_import_row(row, **kwargs)
instance, new = self.get_or_init_instance(instance_loader, row)
self.after_init_instance(instance, new, row, **kwargs)
if new:
row_result.import_type = RowResult.IMPORT_TYPE_NEW
else:
row_result.import_type = RowResult.IMPORT_TYPE_UPDATE
if not skip_diff:
original = deepcopy(instance)
diff = self.get_diff_class()(self, original, new)
if self.for_delete(row, instance):
if new:
row_result.import_type = RowResult.IMPORT_TYPE_SKIP
if not skip_diff:
diff.compare_with(self, None)
else:
row_result.import_type = RowResult.IMPORT_TYPE_DELETE
row_result.add_instance_info(instance)
if self._meta.store_instance:
# create a copy before deletion so id fields are retained
row_result.instance = deepcopy(instance)
self.delete_instance(instance, row, **kwargs)
if not skip_diff:
diff.compare_with(self, None)
else:
import_validation_errors = {}
try:
self.import_instance(instance, row, **kwargs)
except ValidationError as e:
# Validation errors are passed on to validate_instance(),
# where they can be combined with model instance validation
# errors if necessary
import_validation_errors = e.update_error_dict(
import_validation_errors
)
if self.skip_row(instance, original, row, import_validation_errors):
row_result.import_type = RowResult.IMPORT_TYPE_SKIP
else:
self.validate_instance(instance, import_validation_errors)
self.save_instance(instance, new, row, **kwargs)
self.save_m2m(instance, row, **kwargs)
row_result.add_instance_info(instance)
if self._meta.store_instance:
row_result.instance = instance
if not skip_diff:
diff.compare_with(self, instance)
if not new:
row_result.original = original
if not skip_diff and not self._meta.skip_html_diff:
row_result.diff = diff.as_html()
self.after_import_row(row, row_result, **kwargs)
except ValidationError as e:
row_result.import_type = RowResult.IMPORT_TYPE_INVALID
row_result.validation_error = e
except Exception as e:
row_result.import_type = RowResult.IMPORT_TYPE_ERROR
# There is no point logging a transaction error for each row
# when only the original error is likely to be relevant
if not isinstance(e, TransactionManagementError):
logger.debug(e, exc_info=e)
tb_info = traceback.format_exc()
row_result.errors.append(self.get_error_result_class()(e, tb_info, row))
return row_result
def import_data(
self,
dataset,
dry_run=False,
raise_errors=False,
use_transactions=None,
collect_failed_rows=False,
rollback_on_validation_errors=False,
**kwargs,
):
r"""
Imports data from ``tablib.Dataset``. Refer to :doc:`import_workflow`
for a more complete description of the whole import process.
:param dataset: A ``tablib.Dataset``.
:param raise_errors: Whether errors should be printed to the end user
or raised regularly.
:param use_transactions: If ``True`` the import process will be processed
inside a transaction.
:param collect_failed_rows: If ``True`` the import process will collect
failed rows.
:param rollback_on_validation_errors: If both ``use_transactions`` and
``rollback_on_validation_errors`` are set to ``True``, the import process will
be rolled back in case of ValidationError.
:param dry_run: If ``dry_run`` is set, or an error occurs, if a transaction
is being used, it will be rolled back.
:param \**kwargs:
Metadata which may be associated with the import.
"""
if use_transactions is None:
use_transactions = self.get_use_transactions()
db_connection = self.get_db_connection_name()
connection = connections[db_connection]
supports_transactions = getattr(
connection.features, "supports_transactions", False
)
if use_transactions and not supports_transactions:
raise ImproperlyConfigured
using_transactions = (use_transactions or dry_run) and supports_transactions
if self._meta.batch_size is not None and (
not isinstance(self._meta.batch_size, int) or self._meta.batch_size < 0
):
raise ValueError("Batch size must be a positive integer")
with atomic_if_using_transaction(using_transactions, using=db_connection):
result = self.import_data_inner(
dataset,
dry_run,
raise_errors,
using_transactions,
collect_failed_rows,
**kwargs,
)
if using_transactions and (
dry_run
or result.has_errors()
or (rollback_on_validation_errors and result.has_validation_errors())
):
set_rollback(True, using=db_connection)
return result
def import_data_inner(
self,
dataset,
dry_run,
raise_errors,
using_transactions,
collect_failed_rows,
**kwargs,
):
result = self.get_result_class()()
result.diff_headers = self.get_diff_headers()
result.total_rows = len(dataset)
db_connection = self.get_db_connection_name()
try:
with atomic_if_using_transaction(using_transactions, using=db_connection):
self.before_import(dataset, **kwargs)
except Exception as e:
self.handle_import_error(result, e, raise_errors)
self._check_import_id_fields(dataset.headers)
instance_loader = self._meta.instance_loader_class(self, dataset)
# Update the total in case the dataset was altered by before_import()
result.total_rows = len(dataset)
if collect_failed_rows:
result.add_dataset_headers(dataset.headers)
for i, data_row in enumerate(dataset, 1):
row = OrderedDict(zip(dataset.headers, data_row))
with atomic_if_using_transaction(
using_transactions and not self._meta.use_bulk, using=db_connection
):
kwargs.update(
{
"dry_run": dry_run,
"using_transactions": using_transactions,
"row_number": i,
}
)
row_result = self.import_row(
row,
instance_loader,
**kwargs,
)
if self._meta.use_bulk:
# persist a batch of rows
# because this is a batch, any exceptions are logged and not associated
# with a specific row
if len(self.create_instances) == self._meta.batch_size:
with atomic_if_using_transaction(
using_transactions, using=db_connection
):
self.bulk_create(
using_transactions,
dry_run,
raise_errors,
batch_size=self._meta.batch_size,
result=result,
)
if len(self.update_instances) == self._meta.batch_size:
with atomic_if_using_transaction(
using_transactions, using=db_connection
):
self.bulk_update(
using_transactions,
dry_run,
raise_errors,
batch_size=self._meta.batch_size,
result=result,
)
if len(self.delete_instances) == self._meta.batch_size:
with atomic_if_using_transaction(
using_transactions, using=db_connection
):
self.bulk_delete(
using_transactions, dry_run, raise_errors, result=result
)
result.increment_row_result_total(row_result)
if row_result.errors:
if collect_failed_rows:
result.append_failed_row(row, row_result.errors[0])
if raise_errors:
raise row_result.errors[-1].error
elif row_result.validation_error:
result.append_invalid_row(i, row, row_result.validation_error)
if collect_failed_rows:
result.append_failed_row(row, row_result.validation_error)
if raise_errors:
raise row_result.validation_error
if (
row_result.import_type != RowResult.IMPORT_TYPE_SKIP
or self._meta.report_skipped
):
result.append_row_result(row_result)
if self._meta.use_bulk:
# bulk persist any instances which are still pending
with atomic_if_using_transaction(using_transactions, using=db_connection):
self.bulk_create(
using_transactions, dry_run, raise_errors, result=result
)
self.bulk_update(
using_transactions, dry_run, raise_errors, result=result
)
self.bulk_delete(
using_transactions, dry_run, raise_errors, result=result
)
try:
with atomic_if_using_transaction(using_transactions, using=db_connection):
self.after_import(dataset, result, **kwargs)
except Exception as e:
self.handle_import_error(result, e, raise_errors)
return result
def get_import_order(self):
return self._get_ordered_field_names("import_order")
def get_export_order(self):
return self._get_ordered_field_names("export_order")
def before_export(self, queryset, **kwargs):
r"""
Override to add additional logic. Does nothing by default.
:param queryset: The queryset for export.
:param \**kwargs:
Metadata which may be associated with the export.
"""
pass
def after_export(self, queryset, dataset, **kwargs):
r"""
Override to add additional logic. Does nothing by default.
:param queryset: The queryset for export.
:param dataset: A ``tablib.Dataset``.
:param \**kwargs:
Metadata which may be associated with the export.
"""
pass
def filter_export(self, queryset, **kwargs):
r"""
Override to filter an export queryset.
:param queryset: The queryset for export (optional).
:param \**kwargs:
Metadata which may be associated with the export.
:returns: The filtered queryset.