我正在尝试使用 Flask 创建 Web 服务,我的 Web 服务需要返回属于配置文件的所有活动的 json 编码树结构。
我的模型:
class Activity(db.Model):
__tablename__ = 'activity'
id = db.Column(db.Integer, primary_key=True)
profile_id = db.Column(db.String, db.ForeignKey('profile.id'), nullable=False, index=True)
parent_id = db.Column(db.Integer, db.ForeignKey('activity.id'), index=True)
name = db.Column(db.String)
parent = db.relationship('Activiteit', remote_side=[id], backref='children')
class Profile(db.Model):
__tablename__ = 'profile'
id = db.Column(db.Integer, primary_key=True)
profile_name = db.Column(db.String(64))
active = db.Column(db.Boolean, nullable=False)
activities = db.relationship('Activity', backref="profile", lazy='dynamic')
employees = db.relationship('Employee', backref="profile", lazy='dynamic')
我需要以下结构:
Main activity 1
Sub activity 1
Sub activity 2
Subsub activity 1
Main activity 2
etc. etc.
我尝试创建嵌套的字典和字典列表,但每次我都卡住了。最终作为 1 级元素的 3 级元素或仅返回 2 级的树。
经过一番搜索,我发现我需要创建一个带有节点的队列,其中包含一个名称和一个子节点列表,然后将节点添加到树中。
我使用以下函数创建了队列:
def get(self, profile_id):
profile = models.Profile.query.get(profile_id)
queue = {}
for activity in profile.activities:
queue[activity.name]= [c.name for c in activity.children]
现在我不知道如何进行,或者我是否走在正确的道路上。任何帮助都感激不尽
编辑
根据Codegeek 的回答,我创建了以下内容:
def get(self, profile_id):
activities = models.Activity.query.filter_by(profile_id=profile_id).all()
tree = {}
for level1 in activities:
if level1.parent_id is None:
tree[level1.name] = {'id': level1.id}
for level2 in level1.children:
tree[level1.name][level2.name] = {'id': level2.id}
for level3 in level2.children:
tree[level1.name][level2.name][level3.name] = {'id': level3.id}
return tree