is there any simple way to serialize a tree given by a model such as the Category shown below?
I\'d like to get a json object like:
[ { \'name\': \'c
I think you'll have to walk the tree, and build an object which you serialize using JSON. I'm assuming your tree is acyclic, because otherwise it gets more complicated. I haven't tested this, but something like this will work (as long as you're sure you don't have cycles):
def serialize_to_json(self):
return json.dumps(self.serializable_object())
def serializable_object(self):
"Recurse into tree to build a serializable object"
obj = {'name': self.name, 'children': []}
for child in self.get_children():
obj['children'].append(child.serializable_object())
return obj
(Can't remember if children_set
is the right way to get the list of children. Please comment if this is wrong.)
Maybe Tasypie or Django-Piston can help? If not you can have a look at their source code to get some hints on how to do this.