[Fixed]-How do I query objects of all children of a node with Django mptt?



This will get you all category descendants including self.

Assuming that your Product model has a Foreign key category, you can use:



Category.objects.get(pk=1).get_leafnodes() is what you’re looking for.

(django-mptt docs)



Django mptt provides two methods to retrieve children.

From the docs

MPTTModel.get_children(*args, **kwargs)

Returns a QuerySet containing the immediate children of this model >instance, in tree order.

The benefit of using this method over the reverse relation provided by the ORM to the instanceā€™s children is that a database query can be avoided in the case where the instance is a leaf node (it has no children).

If called from a template where the tree has been walked by the cache_tree_children filter, no database query is required.


MPTTModel.get_leafnodes(*args, **kwargs)

Creates a QuerySet containing leafnodes of this model instance, in tree order.

If include_self is True, the QuerySet will also include this model instance (if it is a leaf node)

I’m not sure how your models are set up but I’m not sure why you use mptt here. You are using Category/Product but it seems to be student or people and work groups.

Maybe you can define EstablishmentLevel, Level|, StudentGroup, Student models and instead of using mptt function query something like:


See the Django doc

Hope that helped

Leave a comment