0

I want to clone a django model/object. Here is my code with some debugging statements (method is inside my Item class)

def duplicate_item(self):
    print("original",self.id)
    copy = self
    copy.id = uuid.uuid4()
    print("copy",copy.id)
    copy.save()
    print("What happened",self.id)


This was the output:

original 6a5a8d54-5b45-47fd-abf3-4357aa89dd0c
copy 5b6bfb5f-36b2-4a74-968e-c1f007df9056
what happened 5b6bfb5f-36b2-4a74-968e-c1f007df9056

Why does this happen? I don't know enough about python shallow/deep copy logic so that probably has to do with it. Thank you

Tesuji
  • 1,335
  • 2
  • 12
  • 26
  • 1
    You are not cloning anything, you just assign the same object an alternative name. See [this question](https://stackoverflow.com/questions/4733609/how-do-i-clone-a-django-model-instance-object-and-save-it-to-the-database) about cloning Django model instances. – Selcuk May 23 '19 at 00:30

1 Answers1

1

As @selcuk says, here "you are not cloning anything". You can use this method to clone your object.

Note: you can change this pk as id if your primary key is id

def duplicate_item(self):
    old_data = self.__dict__

    if 'pk' in old_data:
        del old_data['pk']

    if '_state' in old_data:
        del old_data['_state']

    new_object = self.__class__.objects.create(**old_data)
    return new_object

But also you can modify your pk/id by using uuid.uuid4()

def duplicate_item(self):
    old_data = self.__dict__
    old_data['pk'] = uuid.uuid4() # new id

    if '_state' in old_data:
        del old_data['_state']

    new_object = self.__class__.objects.create(**old_data)
    return new_object
binpy
  • 3,994
  • 3
  • 17
  • 54