create table if not exists Menu(
    id serial  primary key ,
    title varchar (50) not null ,
    parent_id int ,
    url varchar (100),
    app_id int ,
    icon varchar (50),
    sortby int default 0,
    create_time timestamp,
    update_time timestamp,
    foreign key (parent_id) references Menu(id) on delete cascade on update cascade

Model 定义

class Menu:
    def __init__(self, id, title, parent_id, url, app_id, icon, sort_by, create_time, update_time, subMenus):
        self._id = id
        self._title = title
        self._parent_id = parent_id
        self._url = url
        self._app_id = app_id
        self._icon = icon
        self._sortby = sort_by
        self._create_time = create_time
        self._update_time = update_time
        self._subMenus = subMenus
    @property
    def id(self):
        return self._id
    @property
    def title(self):
        return self._title
    @property
    def parent_id(self):
        return self._parent_id
    @property
    def url(self):
        return self._url
    @property
    def app_id(self):
        return self._app_id
    @property
    def icon(self):
        return self._icon
    @property
    def sortby(self):
        return self._sortby
    @property
    def subMenus(self):
        return self._subMenus

理论上Models应该中的参数应该和数据库表字段对应,但是subMenus我们不需要存库,反给前端用的。

def set_subMenus(id, menus):
        :param id: 父id
        :param subMenu:子菜单列表
        :return: 没有子菜单返回None 有子菜单返回子菜单列表
        try:
            _subMenus = []
            for menu in menus:
                if menu.parent_id == id:
                    _subMenus.append(menu)
            for sub in _subMenus:
                menu2 = _query_sub_menu_info(sub.id)
                if len(menus):
                    sub._subMenus = set_subMenus(sub.id, menu2)
                else:
                    sub.__delattr__('_subMenus')
            # 子菜单列表不为空
            if len(_subMenus):
                # print(sub_list)
                return _subMenus
            else:  # 没有子菜单了
                return None
        except Exception as e:
            LOG.exception('error query_sub_menu_info !')
            raise e
_query_sub_menu_info 方法是查询返回

测试方法:
def test_sub_menu_list(self):
        Menus = []
        rootMenu = GuardianModelDao._query_root_menu_info()
        for root in rootMenu:
            subMenu = GuardianModelDao._query_sub_menu_info(root.id)
            root = jsonpickle.loads(jsonpickle.encode(root))
            if root.subMenus is not None:
                root.subMenus.append(GuardianModelDao.set_subMenus(root.id, subMenu))
                Menus.append(root)