Skip to main content

Django: Clone a model instance on update

Often times, we need to clone a Django model instance while updating it's fields' values. For example, if we have a price model that needs updating, it needs to be cloned first to keep the current related objects referring to the current pricing values. So while updating, we need to keep the current instance as-is and create a new instance with existing data and update the new instance with updated data instead.

If we don't do the above, when we change any relevant field's value, the related objects will subject to the new values, this will in turn trigger new pricing which would be different from the originally calculated/saved one. This might cause serious reliability problems like the initial price/charge was 20 USD, now it has become 30 USD (for example), and so on.

So to handle this automatic cloning of instances on update, I've written a decorator that can be used as a decorator on the save method of the model. Here it is (all the necesary details are in the docstring):

Read more…