- September 9, 2008
- 3 (after 3 ratings)
Create a copy of a model instance.
Works in model inheritance case where
instance.pk = None is
not good enough, since the subclass instance refers to the
parent_link's primary key during save.
M2M relationships are currently not handled, i.e. they are not copied.
See also Django #4027.
1 2 3 4 5 6 7
from django.db.models import AutoField def copy_model_instance(obj): 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)
More like this
- LazyPrimaryKeyRelatedField by LLyaudet 6 days, 5 hours ago
- CacheInDictManager by LLyaudet 6 days, 11 hours ago
- MYSQL Full Text Expression by Bidaya0 1 week ago
- Custom model manager chaining (Python 3 re-write) by Spotted1270 1 week, 6 days ago
- Django Standard API Response Middleware for DRF for modern frontend easy usage by Denactive 4 weeks, 1 day ago