feincms / django-tree-queries

Adjacency-list trees for Django using recursive common table expressions. Supports PostgreSQL, sqlite, MySQL and MariaDB.
https://django-tree-queries.readthedocs.io/
BSD 3-Clause "New" or "Revised" License
415 stars 27 forks source link

Fetching siblings #61

Closed boosh closed 6 months ago

boosh commented 6 months ago

Do I need to manually query where tree_depth is the same as the node I want siblings for or is there a helper method to retrieve a node's siblings I haven't found? It's not clear from the docs. Thanks

matthiask commented 6 months ago

If you only require siblings you can query the children of the node's parent like so: node.parent.children.all()

No special method is required for this.

boosh commented 6 months ago

That doesn't work for top-level nodes with no parent.

matthiask commented 6 months ago

Yeah, that's true. You can .filter(parent=None) though. Here's almost an one-liner:

def get_siblings_of(node):
    return Node.objects.filter(parent=node)

django-tree-queries doesn't need to add anything like this because you can achieve the same thing by using only Django's own functionality.

boosh commented 6 months ago

OK thanks. I think actually it's highlighted a bug in my code though. All trees should have root nodes :-).