August 25, 2006
[Daniel] Copying A Model Object In Django
Since I found no resources online about this, I thought I ought to post. My situation is that I have an model object in Django and I would like to create a copy of the object so the user can easily duplicate an existing item. This was my solution:
# In views.py...
def copy_object(request, crazy_object_id):
crazy_object_to_copy = get_object_or_404(Crazyobject, pk=crazy_object_id)
new_object = Crazyobject()
new_object.__dict__ = crazy_object_to_copy.__dict__
new_object.id = None
new_object.save()
return HttpResponseRedirect("/crazyobjects/edit/%s" % (new_object.id))
This loads up the old object, creates a new (blank) object and copies over the underlying dictionary. Once this is complete, the "new_object" exactly duplicates the original. Set the id to "None" so it doesn't overwrite the original then save your new object. Finally, reuse your existing edit code via the Redirect.
It feels a little sloppy to me in practice but I'm not sure if there is a better way and it does work, which is good enough for me for the time being.
Permalink
|
Comments (3)
Comments
Ryan
Doesn't work for me, at least with the model I'm using:
IntegrityError: ERROR: null value in column "id" violates not-null constraint
Posted on Oct 5, 2006 @ 12:29 a.m.
Ryan
Actually, it works, I was wrong. This also works:
crazy_object_to_copy = get_object_or_404(Crazyobject, pk=crazy_object_id)
crazy_object_to_copy.id = None
crazy_object_to_copy.save()
(you'd have to get another copy of the original this way though.)
Posted on Oct 5, 2006 @ 1:17 a.m.
Aj
I was able to get this working inside of a generic model using some info from a b-list.org post (nov 03, 2007). Here is my code:
model_class = models.get_model(self._meta.app_label, self._meta.object_name)
copy = model_class()
copy.__dict__ = self.__dict__
copy.pk = None
Thanks much!
Posted on Jul 9, 2008 @ 2:58 p.m.

