This site runs best with JavaScript enabled.

Copy Model Object in Django

Copy Model Object in Django Copy Model Object in Django

I ran into a situation where I wanted to created a new database record from an existing record (model object). I figured there should be a fairly simple solution. It turns out there is and I want to thank Seveas on IRC #django for pointing it out for me. This is essentially what I did:

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

Voila!

Share article
Dustin Davis

Dustin Davis is a software engineer, people manager, hacker, and entreprenuer. He loves to develop systems and automation. He lives with his wife and five kids in Utah.