Copy a model instance

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. Automatically trim newforms text fields by miracle2k 5 years, 8 months ago
  2. Model inheritance with content type and inheritance-aware manager by dan90 4 years, 8 months ago
  3. Random object IDs using an abstract base model by elver 1 year, 10 months ago
  4. GeoDjango maps in admin TabularInlines by alanB 2 years, 7 months ago
  5. duplicate model object merging script by nstrite 5 years, 9 months ago

Comments

asinox (on May 13, 2012):

Try this:

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

#

(Forgotten your password?)