# view文件
from django.shortcuts import render
from app.models import Menu
# Create your views here.
from django.http import JsonResponse
def index(request):
data = get_menu_tree()
return JsonResponse({"list":data})
# 从数据库获取菜单树
def get_menu_tree():
tree = []
menus = Menu.objects.filter(parent=None)
for menu in menus:
menu_data = {
"label":menu.name,
"children":[]
}
childs = Menu.objects.filter(parent=menu)
if childs:
menu_data["children"] = get_child_menu(childs)
tree.append(menu_data)
return tree
# 递归获取所有的子菜单
def get_child_menu(childs):
children = []
if childs:
for child in childs:
data = {
"label":child.name,
"children":[]
}
_childs = Menu.objects.filter(parent=child)
if _childs:
data["children"].append(get_child_menu(_childs))
children.append(data)
return children
# models.py
from django.db import models
class User(models.Model):
username = models.CharField(max_length=16) #创建一个字段,类型为字符串类型,最大长度为16
password = models.CharField(max_length=32) #创建一个字段,类型为字符串类型,最大长度为32
def __unicode__(self):
return self.username
class Menu(models.Model):
name = models.CharField(max_length=64, verbose_name="菜单名称") # 菜单名称
fullName = models.CharField(max_length=512, null=True, blank=True) # 菜单全称
path = models.CharField(max_length=64, null=True, blank=True) # 映射数据路径
parent = models.ForeignKey("Menu", on_delete=models.DO_NOTHING, null=True, blank=True) # 父节点
datum = models.CharField(max_length=64, null=True, blank=True) # 参考基准
type = models.CharField(max_length=64, null=True, blank=True) # 菜单类型
remark = models.CharField(max_length=64, null=True, blank=True) # 备注
def __unicode__(self):
return self.name
def __str__(self):
return self.name
class Meta():
verbose_name = "菜单"
verbose_name_plural = verbose_name
python django 数据库树形菜单的设计