1

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!

Daviddd
  • 761
  • 2
  • 12
  • 37

1 Answers1

1

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()
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • First code is not working as u already wrote with: get() returned more than one MyClass -- it returned 168!',). Hence to get the root node I have to do root_node = MyClass.objects.filter(tree_id=1, level=0) and if I want to get all leaf myClass.objects.filter(lft=F('rght')-1). Right? – Daviddd Jun 11 '14 at 16:54