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
    

  • 相关阅读:
    JS---案例:拖曳对话框
    关于选用ccflow你所担心的问题都在这里为您解答
    Elasticsearch(GEO)数据写入和空间检索
    echart的legend不显示问题
    html5+css3的神奇搭配
    h5+css3+Jq
    初探 jQuery
    在vi编辑器中如何向上翻页,向下翻页以及查询“ab”
    webpack4 特性
    webpack4配置
  • 原文地址:https://www.cnblogs.com/asia9847/p/13071887.html
Copyright © 2011-2022 走看看