Search code examples
djangodjango-contenttypesdjango-polymorphic

Change the polymorphic content type of a django model instance


If I have a polymorphic model:

class Father(polymorphic.model.PolymorphicModel)

and an inheritor class with no extra fields:

class Child(Father)

When I have an instance of Father, how can I convert it to a Child instance?

What I have tried is:

foo = Father.objects.get(pk=1)
# foo is just a Father, no record in Child database table.
foo.polymorphic_ctype = ContentType.objects.get(app_label='myapp', model='child')
foo.save()

But nothing changes. I want foo to be a Child object and need to have this into the child database table.


Solution

  • Ok.

    After reading this similar post I realized that I needed another assignment:

    foo.__class__ = Child
    

    This makes an insertion in the child table otherwise never happened.