django递归菜单

实例代码

from django.shortcuts import render
from .models import Menu

def menu_list(request):
    menus = Menu.objects.filter(parent=None)

    def get_children(menu):
        return Menu.objects.filter(parent=menu)

    def get_menu_tree(menu):
        children = get_children(menu)
        if children:
            return {menu: [get_menu_tree(child) for child in children]}
        return menu

    menu_tree = [get_menu_tree(menu) for menu in menus]

    return render(request, 'menu.html', {'menu_tree': menu_tree})

链接:django 递归菜单-掘金

django 实现完成并用sql实现

你可能感兴趣的:(django,python,后端)