How do I rebuild my django-mptt tree?

十年热恋 提交于 2019-11-28 22:48:42

问题


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?


回答1:


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.




回答2:


work for me:

MenuItem.objects.rebuild()



回答3:


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



回答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).



来源:https://stackoverflow.com/questions/5541432/how-do-i-rebuild-my-django-mptt-tree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!