zoukankan      html  css  js  c++  java
  • python django 数据库树形菜单的设计

    # 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
    

  • 相关阅读:
    修复 XE8 for Android 方向传感器 headingX,Y,Z 不会动的问题
    修复 XE8 for Android 分享图片到 Gmail 权限不足的问题
    Firemonkey 载入 Style 皮肤 (*.fsf 二进制文件) 速度测试
    调整 FMX Android 文字显示「锯齿」效果
    [原创工具] ListView 调色盘 (Free)
    有关Linux的可执行程序
    Android 下配置一个 /dev/fb0 节点出来
    Android下运行Linux可执行程序
    数据库的范式
    rk3128 适配 USB 摄像头
  • 原文地址:https://www.cnblogs.com/asia9847/p/13071887.html
Copyright © 2011-2022 走看看