ddipp
ddipp

Reputation: 159

SQLAlchemy-mptt get full tree

I can't understand how to get the complete object tree 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)

I can make a request:

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

And:

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

But I think that there are easier solutions?

Upvotes: 2

Views: 783

Answers (1)

ddipp
ddipp

Reputation: 159

@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)

And template:

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

Upvotes: 2

Related Questions