Add this method to any model to make it clonable.
1 2 3 | def clone(self):
new_kwargs = dict([(fld.name, getattr(old, fld.name)) for fld in old._meta.fields if fld.name != 'id']);
return self.__class__.objects.create(**new_kwargs)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
This assumes, of course that your primary key is an
AutoField
named"id"
, which won't always be the case. It's easy to make this usable with fields not named"id"
(just changefld.name != 'id'
tofld is not old._meta.pk
), but it's still only valid for models that useAutoField
(which is the default if no primary key field is supplied).This will definitely cover most cases, but for any other field type, you can't just create a new model with no primary key and expect the database to do anything useful with it. I just wanted to note this for anyone trying to use this with such a model, since it's not valid for truly "any" model.
#
It would be useful to accept **kwargs and update new_kwargs accordingly. This would make it possible to clone while changing the values of some fields.
#
Please login first before commenting.