-
-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathmixin.py
733 lines (654 loc) · 28.4 KB
/
mixin.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
import itertools
from itertools import repeat
from typing import List # noqa
from conditional import conditional
from django.core.checks import Error
from django.core.exceptions import ValidationError
from django.db import IntegrityError, connections, models, transaction
from django.db.models import SlugField
from django.utils.text import slugify
from model_clone.apps import ModelCloneConfig
from model_clone.signals import post_clone_save, pre_clone_save
from model_clone.utils import (
clean_value,
context_mutable_attribute,
get_fields_and_unique_fields_from_cls,
get_unique_default,
get_unique_value,
get_value,
transaction_autocommit,
)
class CloneMixin(object):
"""CloneMixin mixin to duplicate an object using the model's class.
:param _clone_fields: Restricted List of fields to copy from the instance.
:type _clone_fields: collections.Iterable
:param _clone_m2m_fields: Many to many fields (Example: TestModel.tags).
:type _clone_m2m_fields: collections.Iterable
:param _clone_m2o_or_o2m_fields: Many to one/One to many fields.
:type _clone_m2o_or_o2m_fields: collections.Iterable
:param _clone_o2o_fields: One to One fields.
:type _clone_o2o_fields: collections.Iterable
:param _clone_linked_m2m_fields: List of fields to link to the cloned instance.
:type _clone_linked_m2m_fields: collections.Iterable
:param _clone_excluded_fields: Excluded model fields.
:type _clone_excluded_fields: collections.Iterable
:param _clone_excluded_m2m_fields: Excluded many to many fields.
:type _clone_excluded_m2m_fields: collections.Iterable
:param _clone_excluded_m2o_or_o2m_fields: Excluded many to many
and one to many fields.
:type _clone_excluded_m2o_or_o2m_fields: collections.Iterable
:param _clone_excluded_o2o_fields: Excluded one to one fields.
:type _clone_excluded_o2o_fields: collections.Iterable
:Example:
>>> from django.conf import settings
>>> from django.db import models
>>>
>>> # Using explicit fields
>>>
>>> class TestModel1(CloneMixin, models.Model):
>>> field_1 = models.CharField(max_length=200)
>>> tags = models.ManyToManyField(Tags)
>>> audiences = models.ManyToManyField(Audience)
>>> user = models.ForiegnKey(
>>> settings.AUTH_USER_MODEL,
>>> on_delete=models.CASCADE,
>>> )
>>>
>>> _clone_m2m_fields = ['tags', 'audiences']
>>> _clone_m2o_or_o2m_fields = ['user']
>>> ...
>>>
>>> # Using implicit all except fields.
>>>
>>> class TestModel2(CloneMixin, models.Model):
>>> field_1 = models.CharField(max_length=200)
>>> tags = models.ManyToManyField(Tags)
>>> audiences = models.ManyToManyField(Audience)
>>> user = models.ForiegnKey(
>>> settings.AUTH_USER_MODEL,
>>> on_delete=models.CASCADE,
>>> null=True,
>>> )
>>> # Clones any other m2m field excluding "audiences".
>>> _clone_excluded_m2m_fields = ['audiences']
>>> # Clones all other many to one or one to many fields excluding "user".
>>> _clone_excluded_m2o_or_o2m_fields = ['user']
>>> ...
"""
# Included fields
_clone_fields = [] # type: List[str]
_clone_m2m_fields = [] # type: List[str]
_clone_m2o_or_o2m_fields = [] # type: List[str]
_clone_o2o_fields = [] # type: List[str]
# Included / linked (not copied) fields
_clone_linked_m2m_fields = [] # type: List[str]
# Excluded fields
_clone_excluded_fields = [] # type: List[str]
_clone_excluded_m2m_fields = [] # type: List[str]
_clone_excluded_m2o_or_o2m_fields = [] # type: List[str]
_clone_excluded_o2o_fields = [] # type: List[str]
DUPLICATE_SUFFIX = "copy" # type: str
USE_DUPLICATE_SUFFIX_FOR_NON_UNIQUE_FIELDS = False # type: bool
UNIQUE_DUPLICATE_SUFFIX = "copy" # type: str
USE_UNIQUE_DUPLICATE_SUFFIX = True # type: bool
MAX_UNIQUE_DUPLICATE_QUERY_ATTEMPTS = 100 # type: int
@classmethod
def check(cls, **kwargs): # pragma: no cover
errors = super(CloneMixin, cls).check(**kwargs)
if cls.USE_UNIQUE_DUPLICATE_SUFFIX and not cls.UNIQUE_DUPLICATE_SUFFIX:
errors.append(
Error(
"UNIQUE_DUPLICATE_SUFFIX is required.",
hint=(
"Please provide UNIQUE_DUPLICATE_SUFFIX"
f" for {cls.__name__} or set USE_UNIQUE_DUPLICATE_SUFFIX=False"
),
obj=cls,
id=f"{ModelCloneConfig.name}.E001",
)
)
if cls.USE_DUPLICATE_SUFFIX_FOR_NON_UNIQUE_FIELDS and not cls.DUPLICATE_SUFFIX:
errors.append(
Error(
"UNIQUE_DUPLICATE_SUFFIX is required.",
hint=(
f"Please provide DUPLICATE_SUFFIX for {cls.__name__} "
"or set USE_DUPLICATE_SUFFIX_FOR_NON_UNIQUE_FIELDS=False"
),
obj=cls,
id=f"{ModelCloneConfig.name}.E001",
)
)
if all([cls._clone_fields, cls._clone_excluded_fields]):
errors.append(
Error(
"Conflicting configuration.",
hint=(
'Please provide either "_clone_fields"'
f' or "_clone_excluded_fields" for model {cls.__name__}'
),
obj=cls,
id=f"{ModelCloneConfig.name}.E002",
)
)
if all([cls._clone_m2m_fields, cls._clone_excluded_m2m_fields]):
errors.append(
Error(
"Conflicting configuration.",
hint=(
'Please provide either "_clone_m2m_fields"'
f' or "_clone_excluded_m2m_fields" for model {cls.__name__}'
),
obj=cls,
id=f"{ModelCloneConfig.name}.E002",
)
)
if all(
[
cls._clone_m2o_or_o2m_fields,
cls._clone_excluded_m2o_or_o2m_fields,
]
):
errors.append(
Error(
"Conflicting configuration.",
hint=(
'Please provide either "_clone_m2o_or_o2m_fields" or '
f'"_clone_excluded_m2o_or_o2m_fields" for model {cls.__name__}'
),
obj=cls,
id=f"{ModelCloneConfig.name}.E002",
)
)
if all([cls._clone_o2o_fields, cls._clone_excluded_o2o_fields]):
errors.append(
Error(
"Conflicting configuration.",
hint=(
'Please provide either "_clone_o2o_fields" or '
f'"_clone_excluded_o2o_fields" for model {cls.__name__}'
),
obj=cls,
id=f"{ModelCloneConfig.name}.E002",
)
)
errors.extend(cls.__check_has_invalid_linked_m2m_fields())
return errors
@classmethod
def __check_has_invalid_linked_m2m_fields(cls):
errors = []
for field_name in cls._clone_linked_m2m_fields:
field = cls._meta.get_field(field_name)
through_field = getattr(field, "field", getattr(field, "remote_field"))
through_model = through_field.through
if not through_model._meta.auto_created:
errors.append(
Error(
f"Invalid configuration for _clone_linked_m2m_fields: {field_name}",
hint=(
'Use "_clone_m2m_fields" instead of "_clone_linked_m2m_fields"'
f" for m2m fields that are not auto-created for model {cls.__name__}"
),
obj=cls,
id=f"{ModelCloneConfig.name}.E003",
)
)
if field_name in cls._clone_excluded_m2m_fields:
errors.append(
Error(
f"Invalid configuration for _clone_excluded_m2m_fields: {field_name}",
hint=(
"Fields that are linked with _clone_linked_m2m_fields "
f"cannot be excluded in _clone_excluded_m2m_fields for model "
f"{cls.__name__}"
),
obj=cls,
id=f"{ModelCloneConfig.name}.E002",
)
)
if field_name in cls._clone_m2m_fields:
errors.append(
Error(
f"Invalid configuration for _clone_m2m_fields: {field_name}",
hint=(
"Fields that are linked with _clone_linked_m2m_fields "
f"cannot be included in _clone_m2m_fields for model {cls.__name__}"
),
obj=cls,
id=f"{ModelCloneConfig.name}.E002",
)
)
return errors
@transaction.atomic
def make_clone(self, attrs=None, sub_clone=False, using=None, parent=None):
"""Creates a clone of the django model instance.
:param attrs: Dictionary of attributes to be replaced on the cloned object.
:type attrs: dict
:param sub_clone: Internal boolean used to detect cloning sub objects.
:type sub_clone: bool
:rtype: :obj:`django.db.models.Model`
:param using: The database alias used to save the created instances.
:type using: str
:return: The model instance that has been cloned.
:param parent: The parent object that is being cloned.
:type parent: :obj:`django.db.models.Model`
"""
using = using or self._state.db or self.__class__._default_manager.db
attrs = attrs or {}
if not self.pk:
raise ValidationError(
"{}: Instance must be saved before it can be cloned.".format(
self.__class__.__name__
)
)
if sub_clone:
duplicate = self # pragma: no cover
duplicate.pk = None # pragma: no cover
else:
duplicate = self._create_copy_of_instance(self, using=using, parent=parent)
for name, value in attrs.items():
setattr(duplicate, name, value)
duplicate = self.__duplicate_m2o_fields(duplicate, using=using)
pre_clone_save.send(sender=self.__class__, instance=duplicate)
duplicate.save(using=using)
duplicate = self.__duplicate_o2o_fields(duplicate, using=using)
duplicate = self.__duplicate_o2m_fields(duplicate, using=using)
duplicate = self.__duplicate_m2m_fields(duplicate, using=using)
duplicate = self.__duplicate_linked_m2m_fields(duplicate)
post_clone_save.send(sender=self.__class__, instance=duplicate)
return duplicate
def bulk_clone(
self, count, attrs=None, batch_size=None, using=None, auto_commit=False
):
using = using or self._state.db or self.__class__._default_manager.db
ops = connections[using].ops
objs = range(count)
clones = []
batch_size = batch_size or max(ops.bulk_batch_size([], list(objs)), 1)
with conditional(
auto_commit,
transaction_autocommit(using=using),
):
# If count exceeds the MAX_UNIQUE_DUPLICATE_QUERY_ATTEMPTS
with conditional(
self.MAX_UNIQUE_DUPLICATE_QUERY_ATTEMPTS < count,
context_mutable_attribute(
self,
"MAX_UNIQUE_DUPLICATE_QUERY_ATTEMPTS",
count,
),
):
if not self.MAX_UNIQUE_DUPLICATE_QUERY_ATTEMPTS >= count:
raise AssertionError(
"An Unknown error has occurred: Expected ({}) >= ({})".format(
self.MAX_UNIQUE_DUPLICATE_QUERY_ATTEMPTS, count
),
)
clones = list(repeat(self.make_clone(attrs=attrs), batch_size))
return clones
@staticmethod
def _create_copy_of_instance(
instance, using=None, force=False, sub_clone=False, parent=None
):
"""Create a copy of a model instance.
:param instance: The instance to be duplicated.
:type instance: `django.db.models.Model`
:param using: The database alias used to save the created instances.
:type using: str
:param force: Flag to skip using the current model clone declared attributes.
:type force: bool
:param sub_clone: Flag to skip cloning one to one fields for sub clones.
:type sub_clone: bool
:return: A new transient instance.
:rtype: `django.db.models.Model`
:param parent: The parent object that is being cloned.
:type parent: :obj:`django.db.models.Model`
"""
cls = instance.__class__
clone_fields = getattr(cls, "_clone_fields", CloneMixin._clone_fields)
clone_excluded_fields = getattr(
cls, "_clone_excluded_fields", CloneMixin._clone_excluded_fields
)
clone_o2o_fields = getattr(
cls, "_clone_o2o_fields", CloneMixin._clone_o2o_fields
)
clone_excluded_o2o_fields = getattr(
cls, "_clone_excluded_o2o_fields", CloneMixin._clone_excluded_o2o_fields
)
unique_duplicate_suffix = getattr(
cls, "UNIQUE_DUPLICATE_SUFFIX", CloneMixin.UNIQUE_DUPLICATE_SUFFIX
)
use_unique_duplicate_suffix = getattr(
cls,
"USE_UNIQUE_DUPLICATE_SUFFIX",
CloneMixin.USE_UNIQUE_DUPLICATE_SUFFIX,
)
max_unique_duplicate_query_attempts = getattr(
cls,
"MAX_UNIQUE_DUPLICATE_QUERY_ATTEMPTS",
CloneMixin.MAX_UNIQUE_DUPLICATE_QUERY_ATTEMPTS,
)
duplicate_suffix = getattr(
cls,
"DUPLICATE_SUFFIX",
CloneMixin.DUPLICATE_SUFFIX,
)
use_duplicate_suffix_for_non_unique_fields = getattr(
cls,
"USE_DUPLICATE_SUFFIX_FOR_NON_UNIQUE_FIELDS",
CloneMixin.USE_DUPLICATE_SUFFIX_FOR_NON_UNIQUE_FIELDS,
)
fields, unique_fields = get_fields_and_unique_fields_from_cls(
model=cls,
force=force,
clone_fields=clone_fields,
clone_excluded_fields=clone_excluded_fields,
clone_o2o_fields=clone_o2o_fields,
clone_excluded_o2o_fields=clone_excluded_o2o_fields,
)
new_instance = cls()
for f in fields:
if not f.editable:
f.pre_save(new_instance, add=True)
continue
value = f.value_from_object(instance)
if all(
[
not f.auto_created,
f.concrete,
f.editable,
f.name in unique_fields,
]
):
# Do not try to get unique value for enum type field
if all(
[
isinstance(f, (models.CharField, models.TextField)),
not f.choices,
isinstance(value, str),
]
):
value = clean_value(value, unique_duplicate_suffix)
if f.has_default():
value = f.get_default()
if not callable(f.default) and isinstance(value, str):
value = get_unique_default(
model=cls,
fname=f.attname,
value=value,
transform=(
slugify if isinstance(f, SlugField) else str
),
suffix=unique_duplicate_suffix,
max_length=f.max_length,
max_attempts=max_unique_duplicate_query_attempts,
)
elif use_unique_duplicate_suffix and isinstance(value, str):
value = get_unique_value(
model=cls,
fname=f.attname,
value=value,
transform=(slugify if isinstance(f, SlugField) else str),
suffix=unique_duplicate_suffix,
max_length=f.max_length,
max_attempts=max_unique_duplicate_query_attempts,
using=using,
)
elif isinstance(f, models.OneToOneField) and not sub_clone:
if parent is not None:
value = parent.pk
else:
sub_instance = (
getattr(instance, f.name, None) or f.get_default()
)
if sub_instance is not None:
sub_instance = CloneMixin._create_copy_of_instance(
sub_instance,
force=True,
sub_clone=True,
using=using,
)
sub_instance.save(using=using)
value = sub_instance.pk
elif all(
[
use_duplicate_suffix_for_non_unique_fields,
f.concrete,
f.editable,
f.name not in unique_fields,
]
):
if (
isinstance(f, (models.CharField, models.TextField))
and not f.choices
):
value = get_value(
value=value,
transform=(slugify if isinstance(f, SlugField) else str),
suffix=duplicate_suffix,
max_length=f.max_length,
)
setattr(new_instance, f.attname, value)
return new_instance
def __duplicate_o2o_fields(self, duplicate, using=None):
"""Duplicate one to one fields.
:param duplicate: The transient instance that should be duplicated.
:type duplicate: `django.db.models.Model`
:param using: The database alias used to save the created instances.
:type using: str
:return: The duplicate instance with all the one to one fields duplicated.
"""
for f in self._meta.related_objects:
if f.one_to_one:
if any(
[
f.name in self._clone_o2o_fields
and f not in self._meta.concrete_fields,
self._clone_excluded_o2o_fields
and f.name not in self._clone_excluded_o2o_fields
and f not in self._meta.concrete_fields,
]
):
rel_object = getattr(self, f.name, None)
if rel_object:
if hasattr(rel_object, "make_clone"):
new_rel_object = rel_object.make_clone(
using=using,
parent=duplicate,
)
else:
new_rel_object = CloneMixin._create_copy_of_instance(
rel_object,
force=True,
using=using,
parent=duplicate,
)
setattr(new_rel_object, f.remote_field.name, duplicate)
new_rel_object.save(using=using)
return duplicate
def __duplicate_o2m_fields(self, duplicate, using=None):
"""Duplicate one to many fields.
:param duplicate: The transient instance that should be duplicated.
:type duplicate: `django.db.models.Model`
:param using: The database alias used to save the created instances.
:type using: str
:return: The duplicate instance with all the transient one to many duplicated instances.
"""
for f in itertools.chain(
self._meta.related_objects, self._meta.concrete_fields
):
if f.one_to_many:
if any(
[
f.get_accessor_name() in self._clone_m2o_or_o2m_fields,
self._clone_excluded_m2o_or_o2m_fields
and f.get_accessor_name()
not in self._clone_excluded_m2o_or_o2m_fields,
]
):
for item in getattr(self, f.get_accessor_name()).all():
if hasattr(item, "make_clone"):
try:
item.make_clone(
attrs={f.remote_field.name: duplicate},
using=using,
)
except IntegrityError:
item.make_clone(
attrs={f.remote_field.name: duplicate},
sub_clone=True,
using=using,
)
else:
new_item = CloneMixin._create_copy_of_instance(
item,
force=True,
sub_clone=True,
using=using,
)
setattr(new_item, f.remote_field.name, duplicate)
new_item.save(using=using)
return duplicate
def __duplicate_m2o_fields(self, duplicate, using=None):
"""Duplicate many to one fields.
:param duplicate: The transient instance that should be duplicated.
:type duplicate: `django.db.models.Model`
:param using: The database alias used to save the created instances.
:type using: str
:return: The duplicate instance with all the many to one fields duplicated.
"""
for f in self._meta.concrete_fields:
if f.many_to_one:
if any(
[
f.name in self._clone_m2o_or_o2m_fields,
self._clone_excluded_m2o_or_o2m_fields
and f.name not in self._clone_excluded_m2o_or_o2m_fields,
]
):
item = getattr(self, f.name)
if hasattr(item, "make_clone"):
try:
item_clone = item.make_clone(using=using)
except IntegrityError:
item_clone = item.make_clone(sub_clone=True, using=using)
elif item is None:
item_clone = None
else:
item_clone = CloneMixin._create_copy_of_instance(
item,
force=True,
sub_clone=True,
using=using,
)
item_clone.save(using=using)
setattr(duplicate, f.name, item_clone)
return duplicate
def __duplicate_m2m_fields(self, duplicate, using=None):
"""Duplicate many to many fields.
:param duplicate: The transient instance that should be duplicated.
:type duplicate: `django.db.models.Model`
:param using: The database alias used to save the created instances.
:type using: str
:return: The duplicate instance with all the many to many fields duplicated.
"""
fields = set()
for f in self._meta.many_to_many:
if any(
[
f.name in self._clone_m2m_fields,
self._clone_excluded_m2m_fields
and f.name not in self._clone_excluded_m2m_fields,
]
):
fields.add(f)
for f in self._meta.related_objects:
if f.many_to_many:
if any(
[
f.get_accessor_name() in self._clone_m2m_fields,
self._clone_excluded_m2m_fields
and f.get_accessor_name()
not in self._clone_excluded_m2m_fields,
]
):
fields.add(f)
# Clone many to many fields
for field in fields:
if hasattr(field, "field"):
# ManyToManyRel
field_name = field.field.m2m_reverse_field_name()
through = field.through
source = getattr(self, field.get_accessor_name())
destination = getattr(duplicate, field.get_accessor_name())
else:
through = field.remote_field.through
field_name = field.m2m_field_name()
source = getattr(self, field.attname)
destination = getattr(duplicate, field.attname)
if all(
[
through,
not through._meta.auto_created,
]
):
objs = through.objects.filter(**{field_name: self.pk})
for item in objs:
if hasattr(through, "make_clone"):
try:
item.make_clone(
attrs={field_name: duplicate},
using=using,
)
except IntegrityError:
item.make_clone(
attrs={field_name: duplicate},
sub_clone=True,
using=using,
)
else:
item.pk = None
setattr(item, field_name, duplicate)
item.save(using=using)
else:
items_clone = []
for item in source.all():
if hasattr(item, "make_clone"):
try:
item_clone = item.make_clone(
using=using,
)
except IntegrityError:
item_clone = item.make_clone(
sub_clone=True,
using=using,
)
else:
item_clone = CloneMixin._create_copy_of_instance(
item,
force=True,
sub_clone=True,
using=using,
)
item_clone.save(using=using)
items_clone.append(item_clone)
destination.set(items_clone)
return duplicate
def __duplicate_linked_m2m_fields(self, duplicate):
"""Duplicate many to many fields.
:param duplicate: The transient instance that should be duplicated.
:type duplicate: `django.db.models.Model`
:return: The duplicate instance objects from all the many-to-many fields duplicated.
"""
for field in self._meta.many_to_many:
if all(
[
field.attname not in self._clone_m2m_fields,
field.attname not in self._clone_excluded_m2m_fields,
field.attname in self._clone_linked_m2m_fields,
]
):
source = getattr(self, field.attname)
destination = getattr(duplicate, field.attname)
destination.set(list(source.all()))
return duplicate