Become a sponsor

分类管理
分类管理模块用于管理树形分类数据,如文章分类、产品分类等。通过 parent_id 字段实现无限级分类。
src/modules/category/
├── models.py # 分类模型
├── schemas.py # 表单验证
├── repository.py # 数据访问层
└── service.py # 业务逻辑层# src/modules/category/models.py
# ============================================================
# 文章分类模型
# ============================================================
class Category(base_model, base_db):
"""文章分类模型类"""
# ============================================================
# 表名配置
# ============================================================
__tablename__ = DB_PREFIX + "category"
__table_comment__ = "文章分类表"
# ============================================================
# 字段定义
# ============================================================
# 分类名称
category_name = Column(String(100), nullable=False, index=True, comment="分类名称")
# 分类编码
category_code = Column(String(100), nullable=True, comment="分类编码")
# 上级ID
parent_id = Column(Integer, default=0, server_default=text('0'), index=True, comment="上级ID")
# 排序
sort = Column(Integer, default=0, server_default=text('0'), comment="排序")
# 分类备注
note = Column(String(100), nullable=True, comment="分类备注")
# ============================================================
# 内置方法
# ============================================================
def __str__(self):
"""返回分类名称"""
return '文章分类{}'.format(self.category_name)字段说明
category_name:分类名称,带索引用于模糊搜索category_code:分类编码,可选字段,用于程序化标识分类parent_id:上级分类 ID,0 表示顶级分类分类通过 parent_id 字段形成树形结构:
文章分类 (parent_id=0)
├── 技术文章 (parent_id=1)
│ ├── 前端技术 (parent_id=2)
│ └── 后端技术 (parent_id=2)
├── 产品动态 (parent_id=1)
└── 公司新闻 (parent_id=1)分类树构建采用与菜单树相同的非递归方案(children_map 分组),避免深层递归性能问题:
def get_tree(data, parent_id):
"""获取树状结构(非递归,children_map 分组)"""
children_map = {}
for item in data:
pid = item["parentId"]
if pid not in children_map:
children_map[pid] = []
children_map[pid].append(item)
def build(pid):
result = []
for item in children_map.get(pid, []):
item["children"] = build(item["id"])
result.append(item)
return result
return build(parent_id)| 接口 | 方法 | 权限节点 | 说明 |
|---|---|---|---|
/api/v1/category/list | GET | sys:category:list | 分类列表 |
/api/v1/category/detail/{id} | GET | sys:category:detail | 分类详情 |
/api/v1/category/add | POST | sys:category:add | 新增分类 |
/api/v1/category/update | PUT | sys:category:update | 编辑分类 |
/api/v1/category/delete/{id} | DELETE | sys:category:delete | 删除分类 |
分类选择通常使用 el-tree 或 el-cascader 组件:
<!-- 树形选择 -->
<el-tree-select
v-model="form.category_id"
:data="categoryTree"
:props="{ label: 'name', value: 'id' }"
/>分类管理模块具备以下特点:
1. 树形结构:parent_id 实现无限级分类,非递归构建树
2. 通用设计:适用于文章分类、产品分类等场景
3. 分类编码:category_code 字段支持程序化标识
4. 排序控制:sort 字段控制分类显示顺序
5. 前端集成:el-tree-select 或 el-cascader 组件
6. 继承 BaseService:声明 page_like_fields/page_eq_fields 即可获得分页能力