Login

Clone method for Django models

Author:
nside
Posted:
July 22, 2008
Language:
Python
Version:
.96
Score:
0 (after 0 ratings)

Add this method to any model to make it clonable.

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. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months 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.

#

Please login first before commenting.