This site runs best with JavaScript enabled.

Copy Model Object in Django

How to copy a database record in Django

Copy Model Object in Django Copy Model Object in Django

Photo by Adam Nieścioruk on Unsplash

I ran into a situation where I wanted to create 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!

Discuss on 𝕏 Edit post on GitHub