【发布时间】:2019-10-08 02:21:36
【问题描述】:
我有一个自引用邻接列表关系,它是我根据 SqlAlchemy 文档创建的。模型如下:
class Menu(db.Model):
id = db.Column(db.Integer, primary_key = True)
title = db.Column(db.String(255))
ordering = db.Column(db.SmallInteger, default = '1')
parent_id = db.Column(db.Integer, db.ForeignKey('menu.id'))
children = db.relationship("Menu",
cascade="all, delete-orphan",
backref = db.backref('parent', remote_side=[id]),
collection_class = attribute_mapped_collection('id'))
我真正想要的是对该模型进行查询并获取如下数据:
root --+---> child1
+---> child2 --+--> subchild1
| +--> subchild2--+--> and so on,
| +--> and so on, if exists
+---> child3 --+--> subchild1
+--> ...
+--> ...
+--> ...
将用以下数据表示:
id parent_id title
--- ------- ----
1 NULL root
2 1 child1
3 1 child2
4 3 subchild1
5 3 subchild2
7 5 so_on1
8 5 so_on2
6 1 child3
9 6 subchild1
如何查询以检索如上所示的数据?
【问题讨论】:
标签: python sqlalchemy