Created
January 15, 2010 01:41
-
-
Save tstone/277703 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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