使用mptt在easyui中显示树形结构
# Django MPTT easyui
## 测试指令
按照MPTT的文档,先创建模型,然后添加数据
from django.db import models
from mptt.models import MPTTModel, TreeForeignKey
class Genre(MPTTModel):
name = models.CharField(max_length=50, unique=True)
parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True)
#class MPTTMeta:
# order_insertion_by = ['name']
注意把order_insertion_by 这里删除。因为在转json输出的时候,按照mptt的lft,id这两个排序。
先清空数据库
from myapp.models import Genre
Genre.objects.all().delete()
创建树节点
from myapp.models import Genre
rock = Genre.objects.create(name="Rock")
blues = Genre.objects.create(name="Blues")
hr = Genre.objects.create(name="Hard Rock", parent=rock)
pr = Genre.objects.create(name="Pop Rock", parent=rock)
Genre.objects.create(name="Hard Rock1", parent=hr)
Genre.objects.create(name="Hard Rock3", parent=hr)
Genre.objects.create(name="Hard Rock2", parent=hr)
## 直接显示mptt
def show_genres(request):
nodes = Genre.objects.all()
#print(nodes)
return render_to_response('genres.html', {'nodes': nodes})
## mptt转json
[fastest way to create JSON to reflect a tree structure in Python / Django using mptt](http://stackoverflow.com/questions/12556268/fastest-way-to-create-json-to-reflect-a-tree-structure-in-python-django-using/12556693)
按照stackflow上的做法,为了快速输出,需要mptt和cache相关的api。然而我这里并不需要快速,额外的要求是输出的顺序,即插入顺序。
def recursive_node_to_dict(node):
result = {
'name': node.name, 'id': node.pk,
#notice the use of node._cached_children instead of node.get_children()
'children' : [recursive_node_to_dict(c) for c in node.get_children().order_by('lft', 'id')]
}
return result
def mptt_json(subTrees):
subRootDicts = []
for subTree in subTrees:
subTree = recursive_node_to_dict(subTree)
subRootDicts.append(subTree)
jsonTree = json.dumps(subRootDicts, indent=4)
print(jsonTree)
# optional clean up, remove the [ ] at the beginning and the end, its needed for D3.js
# jsonTree = jsonTree[1:len(jsonTree)]
# jsonTree = jsonTree[:len(jsonTree)-1]
return jsonTree
def get_tree(request):
rootM = Genre.objects.order_by('lft', 'id').filter(level=0)
json_data = mptt_json(rootM)
# print(json_data)
return HttpResponse(json_data,content_type="application/json")
## easyui加载mptt的数据
<table id="tg" class="easyui-treegrid" title="TreeGrid ContextMenu" style="width:700px;height:250px"
data-options="
iconCls: 'icon-ok',
rownumbers: true,
animate: true,
collapsible: true,
fitColumns: true,
url: '/demo/get_tree/',
method: 'get',
idField: 'id',
treeField: 'name'
">
<thead>
<tr>
<th data-options="field:'name',width:180">Task Name</th>
</tr>
</thead>
</table>

浙公网安备 33010602011771号