Code

Ticket #4027: 4027-model-copy.diff

File 4027-model-copy.diff, 1.4 KB (added by Marek Kubica <pythonmailing@…>, 7 years ago)

Preliniary copy() patch

Line 
1Index: db/models/base.py
2===================================================================
3--- db/models/base.py   (revision 5127)
4+++ db/models/base.py   (working copy)
5@@ -14,6 +14,7 @@
6 from django.utils.functional import curry
7 from django.conf import settings
8 from itertools import izip
9+from copy import copy as copy_object
10 import types
11 import sys
12 import os
13@@ -315,6 +316,29 @@
14 
15     delete.alters_data = True
16 
17+    def copy(self):
18+        """
19+        Returns an already saved copy of this model instance
20+        """
21+        # create a copy of the current object
22+        copied_self = copy_object(self)
23+        # reset the id, save the new object
24+        copied_self.id = None
25+        copied_self.save()
26+
27+        # now, we need to copy all many_to_many related objects
28+        for original, copy in zip(self._meta.many_to_many, copied_self._meta.many_to_many):
29+            # get the managers of the fields
30+            source = getattr(self, original.attname)
31+            destination = getattr(copied_self, copy.attname)
32+            # copy m2m field contents
33+            for element in source.all():
34+                destination.add(element)
35+
36+        # save for a second time (to apply the copied many to many fields)
37+        copied_self.save()
38+        return copied_self
39+
40     def _get_FIELD_display(self, field):
41         value = getattr(self, field.attname)
42         return dict(field.choices).get(value, value)