Search code examples
djangodjango-modelsdjango-orm

Move a python / django object from a parent model to a child (subclass)


I am subclassing an existing model. I want many of the members of the parent class to now, instead, be members of the child class.

For example, I have a model Swallow. Now, I am making EuropeanSwallow(Swallow) and AfricanSwallow(Swallow). I want to take some but not all Swallow objects make them either EuropeanSwallow or AfricanSwallow, depending on whether they are migratory.

How can I move them?


Solution

  • I know this is much later, but I needed to do something similar and couldn't find much. I found the answer buried in some source code here, but also wrote an example class-method that would suffice.

    class AfricanSwallow(Swallow):
    
        @classmethod
        def save_child_from_parent(cls, swallow, new_attrs):
            """
            Inputs:
            - swallow: instance of Swallow we want to create into AfricanSwallow
            - new_attrs: dictionary of new attributes for AfricanSwallow
    
            Adapted from: 
            https://github.com/lsaffre/lino/blob/master/lino/utils/mti.py
            """
            parent_link_field = AfricanSwallow._meta.parents.get(swallow.__class__, None)
            new_attrs[parent_link_field.name] = swallow
            for field in swallow._meta.fields:
                new_attrs[field.name] = getattr(swallow, field.name)
            s = AfricanSwallow(**new_attrs)
            s.save()
            return s
    

    I couldn't figure out how to get my form validation to work with this method however; so it certainly could be improved more; probably means a database refactoring might be the best long-term solution...