简体   繁体   中英

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM