Login

Copy a model instance

Author:
miracle2k
Posted:
September 9, 2008
Language:
Python
Version:
1.0
Score:
3 (after 3 ratings)

Create a copy of a model instance.

Works in model inheritance case where instance.pk = None is not good enough, since the subclass instance refers to the parent_link's primary key during save.

M2M relationships are currently not handled, i.e. they are not copied.

See also Django #4027.

1
2
3
4
5
6
7
from django.db.models import AutoField
def copy_model_instance(obj):
    initial = dict([(f.name, getattr(obj, f.name))
                    for f in obj._meta.fields
                    if not isinstance(f, AutoField) and\
                       not f in obj._meta.parents.values()])
    return obj.__class__(**initial)

More like this

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

Comments

asinox (on May 13, 2012):

Try this:

from copy import deepcopy old_obj = deepcopy(obj) old_obj.id = None old_obj.save()

#

Please login first before commenting.