0

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.

robline
  • 450
  • 4
  • 13

1 Answers1

1

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)
craigds
  • 2,072
  • 14
  • 25
  • Thanks for the response. I am trying to replace the root node with another one. Lets say I have only unearthed part of the tree: node B > node C > node D and later I determine that there is really a node A which is the ancestor for nodes b, c, and d. How would I put node A into that tree and make it the new root? – robline Feb 12 '15 at 21:29
  • 1
    `A = MyNode.objects.create(name='A') ; B.parent = A ; B.save()` would be the standard way to do that. – craigds Feb 12 '15 at 22:02