Finding the child for an inheritable Django model

Rambling on about Django 71 months ago.

On IRC today, someone was asking about a problem which boiled down to finding the matching inherited instance when you have an instance of base class.

Since I enjoy looking around in the database internals, here's a little solution I whipped up. Just attach this to your base Model class:

def child(self):
    from django.core.exceptions import ObjectDoesNotExist
    for related_object in self._meta.get_all_related_objects():
        if not issubclass(related_object.model, self.__class__):
            return getattr(self, related_object.get_accessor_name())
        except ObjectDoesNotExist:

Then base_instance.child will either return a child instance or None.

If you're interested in the _meta internals too, I recommend reading the source here: django/db/models/

Leave a comment or see my other ramblings.

Comments (1)

psyferre said: (71 months ago)

I would have been digging around for how to come up with the child instance for ages. Thanks SmileyChris!

Leave a comment