在Django中序列化树 [英] Serializing a tree in Django
问题描述
是否有任何简单的方法来序列化一个模型给出的树,如下所示的类别?
is there any simple way to serialize a tree given by a model such as the Category shown below?
我想得到一个json对象,如: / p>
I'd like to get a json object like:
[ { 'name': 'cat1',
'children': [ { 'name': 'cat11',
'children': [ ... ]
]
}
...
]
感谢
class Category(MPTTModel):
name = models.CharField(max_length=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)
推荐答案
我想你必须走了树,并构建一个使用JSON序列化的对象。我假设你的树是非循环的,因为否则它变得更复杂。我没有测试过这个,但是这样的事情会奏效(只要你确定没有循环):
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
(不记得如果 children_set
是获取孩子列表的正确方法,请注意,如果这是错误的。)
(Can't remember if children_set
is the right way to get the list of children. Please comment if this is wrong.)
这篇关于在Django中序列化树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!