Initalize

Create model with MPTT mixin:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
from sqlalchemy import Column, Integer, Boolean
from sqlalchemy.ext.declarative import declarative_base

from sqlalchemy_mptt.mixins import BaseNestedSets

Base = declarative_base()


class Tree(Base, BaseNestedSets):
    __tablename__ = "tree"

    id = Column(Integer, primary_key=True)
    visible = Column(Boolean)  # you custom field

    def __repr__(self):
        return "<Node (%s)>" % self.id

It automatically registers events.

Events

But you can do it manually:

from sqlalchemy_mptt import tree_manager

tree_manager.register_events()  # register events before_insert,
                                # before_update and before_delete

Or disable events if it required:

from sqlalchemy_mptt import tree_manager

tree_manager.register_events(remove=True)  # remove events before_insert,
                                           # before_update and before_delete

Data structure

Fill table with records, for example, as shown in the picture

SQLAlchemy MPTT (nested sets)

Represented data of tree like dict

tree = (
    {'id':  '1',                  'parent_id': None},

    {'id':  '2', 'visible': True, 'parent_id':  '1'},
    {'id':  '3', 'visible': True, 'parent_id':  '2'},

    {'id':  '4', 'visible': True, 'parent_id':  '1'},
    {'id':  '5', 'visible': True, 'parent_id':  '4'},
    {'id':  '6', 'visible': True, 'parent_id':  '4'},

    {'id':  '7', 'visible': True, 'parent_id':  '1'},
    {'id':  '8', 'visible': True, 'parent_id':  '7'},
    {'id':  '9',                  'parent_id':  '8'},
    {'id': '10',                  'parent_id':  '7'},
    {'id': '11',                  'parent_id': '10'},
)

Filling data at the first time

When you add any data to the database, he tries to be counted lft, rgt and level attribute. This is done very quickly if the tree already exists in the database, but it is absolutely not allowed for initialize the tree, it is very long. In this case, you can change the code like this:

from sqlalchemy_mptt import tree_manager

...

tree_manager.register_events(remove=True) # Disable MPTT events

# Fill tree
for item in items:
    db.session.add(item)
db.session.commit()

...

tree_manager.register_events() # enabled MPTT events back
models.MyModelTree.rebuild_tree(db.session, models.MyModelTree.tree_id) # rebuild lft, rgt value automatically

After an initial table with tree you can use mptt features.

Session

To work correctly after flush you should use sqlalchemy_mptt.mptt_sessionmaker

1
2
3
4
5
6
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy_mptt import mptt_sessionmaker

engine = create_engine('...')
Session = mptt_sessionmaker(sessionmaker(bind=engine))
  Read the Docs
v: latest  
Versions
latest
Free document hosting provided by Read the Docs.