Search code examples
djangodjango-mptt

django-mptt error on retrieving root nodes of a tree


I am trying to retrieve the root nodes of a hierarchy. My nodes look like this:

class MyNode(MPTTModel):
    parent = TreeForeignKey('self', blank=True, null=True, 
                            related_name='children')
    slug = models.SlugField(max_length=100, unique=True)
    title = models.CharField(max_length=100)
    user = models.ForeignKey(User)

and I call

MyNode.tree.filter(level=0)

to retrieve the root nodes as the documentation says here: http://django-mptt.github.io/django-mptt/technical_details.html#level

But when I execute that code, I get this error:

AttributeError: type object 'MyNode' has no attribute 'tree'

What object am I supposed to use to retrieve the root nodes then? Thank you!


Solution

  • I've been in the same place as you, and I solve that by doing

    MyNode.objects.filter(level=0) # or level=1 or level__lte=1...

    I've read same docs as you and I tried to do like in the example and never make the code running. I hope this solution is enough for you!