Clone method for Django models

1
2
3
        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 5 years, 3 months ago
  2. ROR link_to_remote clone. simple django ajax by qingfeng 5 years, 8 months ago
  3. jstree in change_list for mptt models by pawnhearts 4 years, 1 month ago
  4. Non model specific CSV export of database content by sethtrain 6 years, 2 months ago
  5. FormMail Clone by baumer1122 6 years, 1 month ago

Comments

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.

#

(Forgotten your password?)