您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python django 数据库树形菜单的设计

bubuko 2022/1/25 19:43:29 python 字数 2628 阅读 964 来源 http://www.bubuko.com/infolist-5-1.html

# view文件 from django.shortcuts import render from app.models import Menu # Create your views here. from django.http import JsonResponse def index(requ ...
# 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 数据库树形菜单的设计

原文:https://www.cnblogs.com/asia9847/p/13071887.html


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶