开发者

Serializing a tree in Django

开发者 https://www.devze.com 2023-02-22 21:10 出处:网络
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:

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': 'cat1',
    'children': [ { 'name': 'cat11',
                    'children': [ ... ]
                ]
  }
  ...
]

Thanks

class Category(MPTTModel):
    name = models.CharField(max_len开发者_C百科gth=50, unique=True)
    parent = models.ForeignKey('self', null=True, blank=True, related_name='children')
    order_key = models.IntegerField()

    class Meta:
        verbose_name_plural = 'Categories'

    class MPTTMeta:
        order_insertion_by = ['order_key']

    def __unicode__(self):
        return "%s" %(self.name)


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消