serialize model object to dict with related objects
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | from django.core.exceptions import ObjectDoesNotExist
def model_to_dict(obj, exclude=['AutoField', 'ForeignKey', \
'OneToOneField']):
'''
serialize model object to dict with related objects
author: Vadym Zakovinko <[email protected]>
date: January 31, 2011
http://djangosnippets.org/snippets/2342/
'''
tree = {}
for field_name in obj._meta.get_all_field_names():
try:
field = getattr(obj, field_name)
except (ObjectDoesNotExist, AttributeError):
continue
if field.__class__.__name__ in ['RelatedManager', 'ManyRelatedManager']:
if field.model.__name__ in exclude:
continue
if field.__class__.__name__ == 'ManyRelatedManager':
exclude.append(obj.__class__.__name__)
subtree = []
for related_obj in getattr(obj, field_name).all():
value = model_to_dict(related_obj, \
exclude=exclude)
if value:
subtree.append(value)
if subtree:
tree[field_name] = subtree
continue
field = obj._meta.get_field_by_name(field_name)[0]
if field.__class__.__name__ in exclude:
continue
if field.__class__.__name__ == 'RelatedObject':
exclude.append(field.model.__name__)
tree[field_name] = model_to_dict(getattr(obj, field_name), \
exclude=exclude)
continue
value = getattr(obj, field_name)
if value:
tree[field_name] = value
return tree
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 9 months, 3 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months ago
- Serializer factory with Django Rest Framework by julio 1 year, 4 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 5 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.