Skip to content

Instantly share code, notes, and snippets.

@atdt
Created September 2, 2011 20:24
Show Gist options
  • Save atdt/1189802 to your computer and use it in GitHub Desktop.
Save atdt/1189802 to your computer and use it in GitHub Desktop.
get all children of a django instance
"""
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