Created
February 13, 2013 23:50
-
-
Save guillaumepiot/4949486 to your computer and use it in GitHub Desktop.
Python model instance copy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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