Ticket #4027: 4027-model-copy.diff

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

Preliniary copy() patch

  • db/models/base.py

     
    1414from django.utils.functional import curry
    1515from django.conf import settings
    1616from itertools import izip
     17from copy import copy as copy_object
    1718import types
    1819import sys
    1920import os
     
    315316
    316317    delete.alters_data = True
    317318
     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
    318342    def _get_FIELD_display(self, field):
    319343        value = getattr(self, field.attname)
    320344        return dict(field.choices).get(value, value)
Back to Top