django writedowns

linkaiyi
Follow

Get Exception Messages

except IntegrityError, e: #contains my own custom exception raising with custom messages.
    response_dict.update({'error': str(e)})

get json from mptt

import json
from mptt.templatetags.mptt_tags import cache_tree_children

def recursive_node_to_dict(node):
    result = {
        'id': node.pk,
        'name': node.name,
    }
    children = [recursive_node_to_dict(c) for c in node.get_children()]
    if children:
        result['children'] = children
    return result

root_nodes = cache_tree_children(Node.objects.all())
dicts = []
for n in root_nodes:
    dicts.append(recursive_node_to_dict(n))

print json.dumps(dicts, indent=4)

serialize objects in Django

You can easily use a list to wrap the required object and that’s all what django serializers need to correctly serialize it, eg.:

from django.core import serializers
# assuming obj is a model instance
serialized_obj = serializers.serialize('json', [ obj, ])

or: use model_to_dict

from django.forms.models import model_to_dict

# assuming obj is your model instance
dict_obj = model_to_dict( obj )
Object has 0 attachments

Was this article helpful?

This article is viewed 9 times!

Recent Viewed Articles

0 Comments

Leave a Comment

Support