Created
September 2, 2011 20:24
-
-
Save atdt/1189802 to your computer and use it in GitHub Desktop.
get all children of a django instance
This file contains 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
""" | |
Given a Django model instance, get all of its children. | |
""" | |
__author__ = 'Ori Livneh' | |
__email__ = '[email protected]' | |
from django.core.exceptions import ObjectDoesNotExist | |
def get_children(instance): | |
related = instance._meta.get_all_related_objects() | |
model = type(instance) | |
varnames = (rel.var_name for rel in related if | |
issubclass(rel.model, model)) | |
children = [] | |
for var in varnames: | |
try: | |
children.append(getattr(instance, var)) | |
except ObjectDoesNotExist: | |
pass | |
return children |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment