django-treebeard

In django-treebeard, how to add child for sibling


In my project , i should use tree structure. after seeing documentation of treebeard ,i thought it is well suitable. thanks for providing clear documentation. In documentation, provided the example

    node = get(root.pk).add_child(name='Memory')
    
    get(node.pk).add_sibling(name='Hard Drives')
    <Category: Category: Hard Drives>
    
    get(node.pk).add_sibling(name='SSD')
    <Category: Category: SSD>
    
    get(node.pk).add_child(name='Desktop Memory')

In the above code if i want add child for sibling(ex:Hard Drives),how i can do that


Solution

  • Playing with the example: store objects in variables and use them. Have a look at drives variable below:

        >>> from fora.models import Category
        >>> get = lambda node_id: Category.objects.get(pk=node_id)
        >>> root = Category.add_root(name='Computer Hardware')
        >>> node = get(root.pk).add_child(name='Memory')
        >>> drives = get(node.pk).add_sibling(name='Hard Drives')
        >>> drives.add_child(name='HDD')
        <Category: Category object (4)>
        >>> drives.add_child(name='SDD')
        <Category: Category object (5)>