问题描述
有没有简单的方法来序列化由模型给出的树,例如下面显示的类别?
is there any simple way to serialize a tree given by a model such as the Category shown below?
我想得到一个 json 对象,例如:
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 中序列化一棵树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!