Instantly share code, notes, and snippets.

What would you like to do?
from django.db import models
from django.shortcuts import _get_queryset
class ChildAwareModel(models.Model):
class Meta:
abstract = True
def get_child_model(self):
Attempts to determine if an inherited model record exists.
New child relationships can be added though the inner class Inheritance.
class Model(ChildAwareModel):
class Inheritance:
children = ( 'yourapp.models.ChildModel', )
def get_child_module(module, list):
if len(list) > 1:
return get_child_module(getattr(module, list[0:1][0]), list[1:])
return getattr(module, list[0])
if hasattr(self, 'Inheritance'):
children = getattr(self.Inheritance, 'children', [])
for c in children:
components = c.split('.')
m = __import__(components[0])
klass = get_child_module(m, components[1:])
qs = _get_queryset(klass)
child = qs.get( **{ 'pk' } )
return child
except qs.model.DoesNotExist:
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment