Cloning Django model instance

As you read the Django's documentation, you can easily copy/clone a model isntance as simple as set the pk of the instance to None. Here is the re-usable function:




Noted:
The above method will not clone many_to_many field values of the old model instance. We have to do it like this:

...

# get values of the many_to_many fields of the old model before cloning it
# because after cloning, the old model will actually be the new one
my_m2m_field_value = old_obj.my_m2m_field.all()

# clone a new model instance
new_obj = clone_model_instance(old_obj)
new_obj.my_m2m_field = my_m2m_field_value
new_obj.save()

...

Comments