Skip to content

Commit

Permalink
Added support for modifying the duplicate instance before it's saved (#…
Browse files Browse the repository at this point in the history
…481)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
jackton1 and pre-commit-ci[bot] authored Sep 6, 2021
1 parent e153afb commit 2f054cd
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 0 deletions.
5 changes: 5 additions & 0 deletions model_clone/mixins/clone.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,10 @@ def bulk_clone_multi(cls, objs, attrs=None, batch_size=None):
# TODO: Support bulk clones split by the batch_szie
pass

def pre_save_duplicate(self, instance):
"""Override this method to modify the duplicate instance before it's saved."""
return instance

@transaction.atomic
def make_clone(self, attrs=None, sub_clone=False, using=None):
"""Creates a clone of the django model instance.
Expand Down Expand Up @@ -236,6 +240,7 @@ def make_clone(self, attrs=None, sub_clone=False, using=None):
for name, value in attrs.items():
setattr(duplicate, name, value)

duplicate = self.pre_save_duplicate(duplicate)
duplicate.save(using=using)

duplicate = self.__duplicate_m2o_fields(duplicate, using=using)
Expand Down
5 changes: 5 additions & 0 deletions sample/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,11 @@ class Book(CloneModel):
def __str__(self):
return _(self.name)

def pre_save_duplicate(self, instance):
instance.name = self.name

return instance


class BookTag(models.Model):
book = models.ForeignKey(Book, on_delete=models.CASCADE)
Expand Down

0 comments on commit 2f054cd

Please sign in to comment.