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
    

  • 相关阅读:
    2017-12 CDQZ集训(已完结)
    BZOJ1492 货币兑换 CDQ分治优化DP
    BZOJ2001 [Hnoi2010]City 城市建设 CDQ分治
    树套树小结
    跑路了
    NOI2020 游记
    半平面交模板
    Luogu 3245 大数
    Luogu 3246 序列
    test20190408(十二省联考)
  • 原文地址:https://www.cnblogs.com/asia9847/p/13071887.html
Copyright © 2011-2022 走看看