pythondjangoinheritancemulti-table-inheritance

Django - How can I get a child type object from a parent class object using MTI?


I have a function, get_priority(), which sorts through all objects in a parent class (Chunk) to get the highest 'priority' object. Now I want to get the related subclass object to the superclass object.

The Django docs on Multi-Table Inheritance show that I can do this by using the lowercase name of the subclass. For example, if the subclass was Concept I could do the following:

chunk = get_priority(Chunk.objects.all())
chunk.concept

However, the subclass could be Concept, Code, Formula or Problem. Is the only way to approach this to use try/except for each subclass, e.g.:

chunk = get_priority(Chunk.objects.all())
    try: 
         object = chunk.concept
    except:
        pass
    try:
        object = chunk.code
    except:
        pass
    # etc.

Solution

  • I think that's not the best way to check what kind of child it is, or at least the most simple.

    I guess you have your custom method to get the Chunk priority on get_priority() (Personally I would put it on the Chunk objects manager), so to get the correct child I would do this:

    chunk = get_priority(Chunk.objects.all())
    
    object = None
    for attr in ('concept', 'code', 'formula', 'problem'):
        if hasattr(chunk, attr):
            object = getattr(chunk, attr)
    

    At the end you will have the child in the object variable, or None if it has no child, then you can play with the result in the object like throw an exception if not child found or just pass.