Skip to content

Instantly share code, notes, and snippets.

@tstone
Created January 15, 2010 01:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tstone/277703 to your computer and use it in GitHub Desktop.
Save tstone/277703 to your computer and use it in GitHub Desktop.
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:])
else:
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)
try:
child = qs.get( **{ 'pk':self.pk } )
return child
except qs.model.DoesNotExist:
pass
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment