Skip to content

Instantly share code, notes, and snippets.

@guillaumepiot
Created February 13, 2013 23:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guillaumepiot/4949486 to your computer and use it in GitHub Desktop.
Save guillaumepiot/4949486 to your computer and use it in GitHub Desktop.
Python model instance copy
def copy_model_instance(obj):
"""
Create a copy of a model instance.
M2M relationships are currently not handled, i.e. they are not copied. (Fortunately, you don't have any in this case)
See also Django #4027. From http://blog.elsdoerfer.name/2008/09/09/making-a-copy-of-a-model-instance/
"""
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment