# 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
