Edgar Navasardyan Edgar Navasardyan - 2 months ago 13
Python Question

Django - how do I clone object without applying clone changes to source object

Best described by example:

View:

def my_view(request):
obj_old = Inventories.objects.get(id = source_id)
obj_new = obj_old
obj_old.some_field = 0
obj_old.save()

obj_new.some_field = 1
obj_new.id = None
obj_new.save()


The problem is that the changes I make to obj_new are also applied to
obj_old
so that the value of
some_field
is 1 for both
obj_old
and
obj_new
. Any ideas how to fix this ?

Answer

You should make a copy of your object, and not make them equal.

To make a copy you can use the copy module

import copy

obj_new = copy.deepcopy(obj_old)
Comments