Proposal: Add a method to create a copy of a model instance

Currently the documented way to create a copy of a model instance is by setting its pk to None and saving the instance again - see link. It also states that there is no built-in method for copying model instances. I’m not sure if such a method was not provided by design, but from my research through Trac and the forum, I couldn’t find a reason as to why it can’t/shouldn’t exist.

Would it be feasible to add such a method? We could then expose parameters to control exactly how the instance is copied (with or without FK or M2M relations, what should be done about OneToOneFields, and so on).

1 Like

Through git blame on the documentation section, I found the related commit and ticket. There’s a lengthy discussion on the ticket about the complexities with M2M fields etc.

I think at this point it would need some deep research and testing to present a possible solution. It may also best to iterate on a solution in a third party package.

I agree that there are complexities with M2M and related fields, but if it would be okay to have a simpler implementation (possibly without support for deep copying and leaving out the case of inherited models, etc.), I’d like to take a stab at implementing this.

Just wanted to make sure that the idea wasn’t too outrageous!

Like Adam touched on, often a good idea is to try out implementing it as a 3rd party package and share it with people. If it’s something that becomes quite popular and takes off then it could be considered a candidate for inclusion into the core framework.

In this particular case there’s no reason why it couldn’t start out as a separate function instead of an instance method.

Also just FYI another good option is to propose it for inclusion into django-exensions: they have a great selection of niche extensions for Django. It might be a great way to gauge it’s usefulness for inclusion into core like shell_plus which has been considered as a nice prototype for improving core’s shell.

Also just FYI another good option is to propose it for inclusion into django-extensions.

That seems like a better fit for this feature. I’ll do that. Thanks!