Clone model mixin

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import copy


class ClonableMixin(object):
    def clone(self):
        """Return an identical copy of the instance with a new ID."""
        if not self.pk:
            raise ValueError('Instance must be saved before it can be cloned.')
        duplicate = copy.copy(self)
        # Setting pk to None tricks Django into thinking this is a new object.
        duplicate.pk = None
        duplicate.save()
        # ... but the trick loses all ManyToMany relations.
        for field in self._meta.many_to_many:
            source = getattr(self, field.attname)
            destination = getattr(duplicate, field.attname)
            for item in source.all():
                destination.add(item)
        return duplicate

More like this

  1. Clone method for Django models by nside 4 years, 10 months ago
  2. Allow filtering and ordering by counts of related query results by exogen 6 years, 1 month ago
  3. ManyToMany field with newforms by lawgon 5 years, 5 months ago
  4. Copy a model instance by miracle2k 4 years, 8 months ago
  5. RelatedMixin for Details and Updates with Related Object Lists by christhekeele 12 months ago

Comments

rizumu (on October 22, 2009):

On django 1.2, this snippet works for me only if i set both pk and id to None:

# Setting both pk and id to None tricks Django into thinking this is a new object.
duplicate.pk = None
duplicate.id = None

#

(Forgotten your password?)