Understand tree fields (tree_depth, tree_path, tree_ordering)
mainWhen using .with_tree_fields(), each node is annotated with:
tree_depth: Integer representing depth (root is 0).tree_path: Array of primary keys from root to the current node.tree_ordering: Array of the ordering/ranking values used for sibling ordering at each level.
Note: Tree fields are calculated at query time via a recursive CTE and are NOT stored in the database. They are unavailable immediately after .create(), .save(), or .refresh_from_db(). You must re-query using .with_tree_fields() to access them.
# Correct way to access tree fields after creation
new_node = Node.objects.create(name="New Child", parent=parent_node)
new_node = Node.objects.with_tree_fields().get(pk=new_node.pk)
print(new_node.tree_depth)