| | 319 | def copy(self): |
| | 320 | """ |
| | 321 | Returns an already saved copy of this model instance |
| | 322 | """ |
| | 323 | # create a copy of the current object |
| | 324 | copied_self = copy_object(self) |
| | 325 | # reset the id, save the new object |
| | 326 | copied_self.id = None |
| | 327 | copied_self.save() |
| | 328 | |
| | 329 | # now, we need to copy all many_to_many related objects |
| | 330 | for original, copy in zip(self._meta.many_to_many, copied_self._meta.many_to_many): |
| | 331 | # get the managers of the fields |
| | 332 | source = getattr(self, original.attname) |
| | 333 | destination = getattr(copied_self, copy.attname) |
| | 334 | # copy m2m field contents |
| | 335 | for element in source.all(): |
| | 336 | destination.add(element) |
| | 337 | |
| | 338 | # save for a second time (to apply the copied many to many fields) |
| | 339 | copied_self.save() |
| | 340 | return copied_self |
| | 341 | |