Serializing a tree in Django

后端 未结 2 434
一生所求
一生所求 2021-01-13 18:35

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         


        
相关标签:
2条回答
  • 2021-01-13 19:18

    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.)

    0 讨论(0)
  • 2021-01-13 19:22

    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.

    0 讨论(0)
提交回复
热议问题