分类标签children,具体内容是?
摘要:class getcontentTag(MethodView): def get(self): try: _sql_cate = "SELECT * FROM cate_a" cate_r
class getcontentTag(MethodView):
def get(self):
try:
_sql_cate = "SELECT * FROM cate_a"
cate_res = db.session.execute(text(_sql_cate)).fetchall()
_sql_tag = "SELECT * FROM tag_a"
tag_res = db.session.execute(text(_sql_tag)).fetchall()
#将查询结果转换为字典列表
categories = [dict(row._asdict()) for row in cate_res]
tags = [dict(row._asdict()) for row in tag_res]
# 构建类别字典,key为id,value为类别信息
category_dict = {category['id']: category for category in categories}
# print(category_dict)
# # 初始化children列表
for category in categories:
# 空列表,存储子标签
category['children'] = []
# print(category)
# #将标签添加到对应的类别中
for tag in tags:
# print(tag)
# # 如pid在category_dict中,则将标签添加到对应的类别中
if tag['pid'] in category_dict:
# # 将标签添加到对应的类别的children列表中
category_dict[tag['pid']]['children'].append(tag)
# # 提取根类别
result = [category for category in categories if category['pid'] == 0]
return jsonify({'code': Code.OK, 'msg': code_desc[Code.OK], 'data':result})
except Exception as e:
return jsonify({'code': Code.ERROR, 'msg': code_desc[Code.ERROR], 'data': None})
{
"code": 200,
"data": [
{
"children": [
{
"id": 1,
"name": "体育鞋测评",
"pid": 1
},
{
"id": 2,
"name": "耳机评测",
"pid": 1
}
],
"id": 1,
"name": "产品评测",
"pid": 0
},
{
"children": [
{
"id": 3,
"name": "扑克",
"pid": 2
