Clone method for Django models

July 22, 2008
django models clone
0 (after 0 ratings)

Add this method to any model to make it clonable.

        def clone(self):
                new_kwargs = dict([(fld.name, getattr(old, fld.name)) for fld in old._meta.fields if fld.name != 'id']);
                return self.__class__.objects.create(**new_kwargs)

More like this

  1. Clone model mixin by zakj 6 years, 2 months ago
  2. ROR link_to_remote clone. simple django ajax by qingfeng 6 years, 7 months ago
  3. jstree in change_list for mptt models by pawnhearts 5 years ago
  4. Non model specific CSV export of database content by sethtrain 7 years ago
  5. FormMail Clone by baumer1122 6 years, 11 months ago


Gulopine (on July 22, 2008):

This assumes, of course that your primary key is an AutoField named "id", which won't always be the case. It's easy to make this usable with fields not named "id" (just change fld.name != 'id' to fld is not old._meta.pk), but it's still only valid for models that use AutoField (which is the default if no primary key field is supplied).

This will definitely cover most cases, but for any other field type, you can't just create a new model with no primary key and expect the database to do anything useful with it. I just wanted to note this for anyone trying to use this with such a model, since it's not valid for truly "any" model.


akaihola (on August 5, 2008):

It would be useful to accept **kwargs and update new_kwargs accordingly. This would make it possible to clone while changing the values of some fields.


Please login first before commenting.