Search code examples
javascriptdjangodjango-mptt

Find Second Level Children In Django Mptt


I have a model that have a field like this:

parent = TreeForeignKey('self', null=True, blank=True, related_name='children')

I want to add parent to a select box and then with onclick, select the second level children.

parent1
-section1
--child1

parent2
-section2
--child2

I have tried all things. (level__gt), (level__lt) ....I have read the django-mptt document. How can I fetch second child? I dont want use ul and li. I want to add all parents in a select and then fetch second children with clik to parents.

Any help would be appreciated.


Solution

  • not sure to fully understand your question. Here some shortcuts:

    # all 2^ level 
    Model.objects.filter(level=1)
    
    # all leafs (any level)
    Model.objects.filter(lft=F('rght') - 1)
    
    # the whole tree except the first node
    Model.objects.filter(tree_id=1)[1:]
    
    # all the nodes with childs
    Model.objects.exclude(tree_id=1)
    
    # all childs of a node
    node.get_children()
    
    # the whole tree of a node (from the top to the last child)
    Model.objects.filter(tree_id=node.tree_id)