SQLAlchemy-mptt得到完整的树

时间:2016-03-16 05:03:01

标签: python sqlalchemy flask-sqlalchemy

我无法理解如何获取完整的对象树SQLAlchemy-mptt:

from sqlalchemy_mptt import BaseNestedSets

class Category(db.Model, BaseNestedSets):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column('Text', db.String(120))

    def __repr__(self):
        return "<Category (id={0}, name={1}, parent={2})>".format(self.id, self.name,
                                                                  self.parent_id)

我可以提出请求:

roots = Category.query.filter_by(parent_id=None)

full_tree = None
for root in roots:
    full_tree += root.drilldown_tree()

但我认为有更简单的解决方案吗?

1 个答案:

答案 0 :(得分:2)

@app.route('/test')
def test():
    title = "Page for tree test"
    roots = Category.query.filter_by(parent_id=None)
    full_tree = []
    for root in roots:
        full_tree.append(root.drilldown_tree()[0])
    return render_template('test.html', title=title, category=full_tree)

模板:

{%- for item in category recursive %}
    <p>{{ '+--' * (loop.depth-1) }}{{item.node.name}}</p>
    {%- if item.children -%}
        {{ loop(item.children) }}
    {%- endif %}
{%- endfor %}