Search code examples
pythondjangodjango-mptt

django-mptt multiple trees and queryset


My model Class can contain multiple trees.

class MyClass(MPTTModel, AbstractClass):
    """
    """
    name = models.CharField(_('name'), max_length=255)
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children')
    ***

I suppose I could do:

nodes = MyClass.objects.filter(tree_id=1)

And using:

nodes.get_root(), nodes.get_children(), etc,

But I have

str: 'QuerySet' object has no attribute 'get_root'

Reading the DOC "Subclasses of MPTTModel have the following instance methods: *"

How can I use the methods having multiple trees in one model class?

Thanks!


Solution

  • You are calling get_root() and other methods on a queryset. Instead, you need to call them on model instances. To get the instance by id use get():

    node = MyClass.objects.get(tree_id=1)
    node.get_root()
    

    Or, if you are filtering multiple objects, loop over the resulting queryset:

    nodes = MyClass.objects.filter(some_conditions)
    for node in nodes:
        node.get_root()