17

I'm using django-mptt 0.4.2, and want to rebuild a tree.

The tree manager has a method rebuild() which I try to access like this:

>>> my_rootnode = MyObj.objects.get(id=12)
>>> my_rootnode.tree.rebuild()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/manager.py", line 211, in __get__
    raise AttributeError("Manager isn't accessible via %s instances" % type.__name__)
AttributeError: Manager isn't accessible via MyObj instances

I'm obviously doing this wrong. How should I access the rebuild method?

manji
  • 47,442
  • 5
  • 96
  • 103
Hobhouse
  • 15,463
  • 12
  • 35
  • 43

4 Answers4

22

work for me:

MenuItem.objects.rebuild()
iqmaker
  • 2,162
  • 25
  • 24
20

AttributeError: Manager isn't accessible via MyObj instances

mptt Manager inherits from django.db.models.Manager which can not be accessed via model instances but only via model classes. More infos:Retrieving objects

The model class here is MyObj. You are using a model instance my_rootnode

the correct usage is:

MyObj.tree.rebuild() (documentation link)

this will build MyObj tree.

manji
  • 47,442
  • 5
  • 96
  • 103
  • 8
    In Django-MPTT 0.9.1 this gives an AttributeError: `AttributeError: type object 'Node' has no attribute 'tree'`. Looks like `MyObj.objects.rebuild()` is the way to go now, though that doesn't seem to work in a migration script because for some reason the Manager isn't a TreeManager then. In the shell all is good. Odd. – partofthething Oct 24 '18 at 18:25
7

Recent MPTT version seem to require the following command. At least it worked for me today, although dash in front indicates that tree manager is private, and probably should not be accessed directly:

MyObj._tree_manager.rebuild()
fafagitolo
  • 79
  • 1
  • 2
  • Note that MyObj should be the actual Model Class and not an object. Tested with Django-MPTT 0.8.7 - It rebuilt my broken relations, but there was still an issue with my root categories which were parentless. – JxAxMxIxN May 29 '17 at 23:53
  • This is correct as of version 0.9 (2022) – Tomislav Urban May 04 '22 at 18:34
4

manji is indeed right, you need to use the model class to call rebuild.

However, if you want to rebuild the tree only for a specific object and its descendants, you can use :

MyObj.tree.partial_rebuild(tree_id).

pistache
  • 5,782
  • 1
  • 29
  • 50
  • 3
    Note that partial_rebuild is not yet part of an official release which is as of today 0.5.5. Thus if you install via pip partial_rebuild will not be available. Anyhow you could use the master branch directly from github. See this: https://github.com/django-mptt/django-mptt/issues/250 .. – Thomas Kremmel May 11 '13 at 15:59
  • It's now part of 0.6.0 release. – chhantyal Jan 23 '14 at 10:37