I have a ModelBase, and ModelA, ModelB.
I want to change ModelA instance to ModelB instance. (I can handle the difference of attributes they have)
I've seen related questions but doesn't quite work for me.
How can I create an inherited django model instance from an existing base model instance?
Change class of child on django models
- EDIT
When you have Place - Restaurant/Bar relationship,
I think it's quite reasonable to be able to switch a restaurant to a bar.
I had to deal with the same problem, both yuvi and arctelix answers did not work for me. yuvi solution gives an error and arctelix solution creates new object with new pk.
The goal here is to change the subclass model while keeping the original superclass as it is with the old pk.
First: Delete the old subclass and keep the superclass.Check Django documents.
Second: Add the new subclass with its fields and pass the superclass to it. Check this q
Example: A place could be a restaurant or a caffe, and you want to change a restaurant place to a caffee; as follow:
I would create an entirely new instance of the second model with the same values of their shared attributes, then delete the old one. Seems like the cleanest way to me.
If ModelBase is abstract:
If ModelBase is not abstract, however, you'll have to do an extra workaround:
In yuvi's answer manually assigning modelbase_ptr and saving fails since instance.modelbase_ptr is deleted prior to save.
Building on yuvi's answer here a more explicit example and works generically for abstract and non-abstract conversions of:
Optionally preserves the original id and this follows the django docs recomended methodology.
In Class ModelBase: