Search code examples
pythondjangodjango-mpttfactory-boy

Add a new root node to django-mptt tree


How can I add a new root node to an existing tree in django-mptt? I am using Django 1.7.4 and django-mptt==0.6.1 with FactoryBoy to test trees. I tried the following:

my_leaf.move_to(my_root, position='left') # creates a new tree
my_leaf.move_to(None, position='this_is_ignored') # also creates a new tree

newroot = factories.MyFactory.build(parent=None, name="NewRoot")
newroot.insert_at(self.my_root, position='left', save=True) 

Everything I do creates a new tree.


Solution

  • A tree has one root node. If you're trying to add a new root node, it means adding a new tree. django-mptt supports either having one tree (just only create one root node), or a whole forest of trees.

    You basically never need to use .move_to(), unless you're doing something really special like manually-user-ordered nodes. Just set the parent to None. I don't know much about FactoryBoy but the usual way to create a new root node is just:

    MyNode.objects.create(name='NewRoot', parent=None)