### Install django-fast-treenode Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/installation.md Install the package using pip. This is the first step for new projects. ```sh pip install django-fast-treenode ``` -------------------------------- ### Uninstall django-treenode and Install django-fast-treenode Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/migration.md Begin the migration from django-treenode by uninstalling the old package and installing the new one. ```bash pip uninstall django-treenode pip install django-fast-treenode ``` -------------------------------- ### Clear Table and Install Django-Fast-Treenode Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/migration.md Commands to clear the existing data from the Category table and then uninstall django-treebeard before installing django-fast-treenode. ```python Category.objects.all().delete() ``` ```bash pip uninstall django-treebeard ``` ```bash pip install django-fast-treenode ``` -------------------------------- ### Run Django Development Server Source: https://github.com/timurkady/django-fast-treenode/blob/main/README.md Start the Django development server to view your application. This command is used for local development and testing. ```sh python manage.py runserver ``` -------------------------------- ### Backup Database with dumpdata Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/migration.md Create a full backup of your database using Django's dumpdata command before starting the upgrade process. ```bash python manage.py dumpdata > backup.json ``` -------------------------------- ### Get Siblings Primary Keys Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Returns a list of primary keys for all sibling nodes. ```python obj.get_siblings_pks() ``` -------------------------------- ### Get Family Primary Keys Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Returns a list of primary keys for the node, its ancestors, and its descendants, in tree order. ```python obj.get_family_pks() ``` -------------------------------- ### Retrieve Tree Structure via API Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/apifirst.md Use a GET request to the tree endpoint to fetch the entire tree structure. ```bash GET treenode/api/category/tree/ ``` -------------------------------- ### Get Root Node Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Retrieves the root node for the current node. ```python obj.get_root() ``` -------------------------------- ### Get All Root Nodes Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Returns a list containing all root nodes in the tree. ```python cls.get_roots() ``` -------------------------------- ### Retrieve All Nodes via API Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/apifirst.md Send a GET request to the API endpoint to list all nodes. The nodes will be ordered according to the tree structure. ```bash GET treenode/api/category/ ``` -------------------------------- ### Get Siblings List Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Returns a list of all sibling nodes for the current node. ```python obj.get_siblings() ``` ```python obj.siblings ``` -------------------------------- ### Get Family List Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Returns a list containing the node, its ancestors, and its descendants, in tree order. ```python obj.get_family() ``` -------------------------------- ### Customizing Meta Class with Additional Indexes Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/models.md Extend TreeNodeModel.Meta to preserve essential indexing and add custom database indexes. This example adds an index on the 'name' field. ```python class Category(TreeNodeModel): treenode_display_field = "name" name = models.CharField(max_length=50) class Meta(TreeNodeModel.Meta): verbose_name = "Category" verbose_name_plural = "Categories" indexes = list(TreeNodeModel._meta.indexes) + [ models.Index(fields=["name"]), ] ``` -------------------------------- ### Upgrade django-fast-treenode Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/installation.md Upgrade to the latest version of the package. Essential when switching from other treenode packages or upgrading an existing installation. ```sh pip install --upgrade django-fast-treenode ``` -------------------------------- ### Get Children Primary Keys Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Retrieves a list of primary keys for all direct children of a node. ```python obj.get_children_pks() ``` -------------------------------- ### Get Tree Structure Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Returns an n-dimensional dictionary representing the model tree. If an instance is provided, it returns a subtree rooted at that instance. ```python cls.get_tree(instance=None) ``` -------------------------------- ### Get Parent Primary Key Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Retrieves the primary key (PK) of the parent node. ```python obj.get_parent_pk() ``` -------------------------------- ### Get Siblings Queryset Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Returns the queryset containing all sibling nodes for the current node. ```python obj.get_siblings_queryset() ``` -------------------------------- ### Get Tree as JSON String Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Represents the tree structure as a JSON-compatible string. An optional instance can be provided to represent a subtree. ```python cls.get_tree_json(instance=None) ``` -------------------------------- ### Get Root Node Primary Key Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Retrieves the primary key (PK) of the root node for the current node. ```python obj.get_root_pk() ``` -------------------------------- ### Get Root Nodes Primary Keys Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Returns a list containing the primary keys (PKs) of all root nodes in the tree. ```python cls.get_roots_pks() ``` -------------------------------- ### Access breadcrumbs Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Get a list representing the path from the root to the current node, including the node itself. Useful for navigation displays. ```python obj.breadcrumbs ``` -------------------------------- ### Secure Auto-Generated API with PermissionRequiredMixin Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/customization.md Extend `AutoTreeAPI` with Django's `PermissionRequiredMixin` to protect all auto-generated API endpoints. This example requires the 'myapp.change_category' permission. ```python from django.contrib.auth.mixins import PermissionRequiredMixin from treenode.views.autoapi import AutoTreeAPI class SecuredTreeAPI(PermissionRequiredMixin, AutoTreeAPI): permission_required = 'myapp.change_category' raise_exception = True ``` -------------------------------- ### Get Ancestors Primary Keys Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Returns a list of primary keys for all ancestor nodes. Useful for optimized database queries. ```python obj.get_ancestors_pks(include_self=True, depth=None) ``` -------------------------------- ### Get Annotated Tree List Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Returns an annotated list from a tree branch, ordered by materialized path. This format is useful for UI display. ```python cls.get_tree_annotated() ``` -------------------------------- ### Get Materialized Path Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Retrieves the materialized path of a node, constructed by tracing its position through ancestors. ```python obj.get_path(prefix='', suffix='', delimiter='.', format_str='') ``` -------------------------------- ### Get Children Queryset Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Returns a queryset containing all direct child nodes of the current node. ```python obj.get_children_queryset() ``` -------------------------------- ### Get Family Queryset Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Returns a QuerySet containing the ancestors, the node itself, and its descendants, ordered according to the tree structure. ```python obj.get_family_queryset() ``` -------------------------------- ### Get Ancestors List Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Retrieves a list containing all ancestor nodes, ordered from the root down to the immediate parent. ```python obj.get_ancestors(include_self=True, depth=None) ``` -------------------------------- ### Get First Root Node Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Retrieves the first root node in the tree. Returns None if the tree is empty. ```python cls.get_first_root() ``` -------------------------------- ### Get Descendants Primary Keys Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Returns a list of primary keys for all descendant nodes. Options to include the self node and limit depth are available. ```python obj.get_descendants_pks(include_self=False, depth=None) ``` -------------------------------- ### Get Children Nodes Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Retrieves a list containing all direct child nodes of a given node. ```python obj.get_children() ``` -------------------------------- ### Get Next Sibling Node Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Returns the next sibling node in the tree, or None if no next sibling exists. ```python obj.get_next_sibling() ``` -------------------------------- ### Implement Permission Check in Model Method Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/customization.md Add custom permission logic within model methods to control sensitive operations like moving nodes. This example checks if the current user has permission to move a category. ```python from django.core.exceptions import PermissionDenied from treenode.models import TreeNodeModel class Category(TreeNodeModel): treenode_display_field = "name" def move_to(self, target, position='last-child'): if not self.can_user_move(self.current_user): # Your custom logic raise PermissionDenied("You are not allowed to move this node.") return super().move(target, position) def can_user_move(self, user): # Define your project-specific rules here return user.is_staff or self.owner == user ``` -------------------------------- ### Access node depth Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Get the depth of the current node from the root. The root node typically has a depth of 0. ```python obj.depth ``` -------------------------------- ### Get First Child Node Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Retrieves the first direct child node. Returns None if the node has no children. ```python obj.get_first_child() ``` -------------------------------- ### Get Node Level Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Returns the level of the node within the tree, starting from 1 for the root. ```python obj.get_level() ``` -------------------------------- ### Get Node Depth Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Calculates and returns the depth of the node within the tree, starting from 0 for the root. ```python obj.get_depth() ``` -------------------------------- ### Get Descendants Queryset Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Returns a queryset of all descendant nodes. Options to include the self node and limit depth are available. ```python obj.get_descendants_queryset(include_self=False, depth=None) ``` -------------------------------- ### Get Descendants List Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Returns a list containing all descendant nodes. Options to include the self node and limit depth are available. ```python obj.get_descendants(include_self=False, depth=None) ``` -------------------------------- ### Add Custom Method to TreeNode Model Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/customization.md Extend your TreeNode model with custom methods to encapsulate specific behaviors. This example adds a method to retrieve descendants as a flat list. ```python from treenode.models import TreeNodeModel class Category(TreeNodeModel): def get_descendants_flat(self): return list(self.get_descendants_queryset()) ``` -------------------------------- ### Apply Django Migrations Source: https://github.com/timurkady/django-fast-treenode/blob/main/README.md Apply database migrations to create the necessary tables for your tree model. Run makemigrations and migrate commands. ```sh python manage.py makemigrations python manage.py migrate ``` -------------------------------- ### Get Breadcrumbs Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Generates breadcrumbs to the current node, optionally specifying an attribute to use for the breadcrumb trail. Defaults to primary keys. ```python obj.get_breadcrumbs(attr=None) ``` -------------------------------- ### Configure Login URL in Settings Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/apifirst.md Set the LOGIN_URL in your project's settings.py to specify the redirect location for unauthorized users. ```python LOGIN_URL = '/accounts/login/' ``` -------------------------------- ### Get Siblings Count Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Returns the total count of sibling nodes. ```python obj.get_siblings_count() ``` -------------------------------- ### Get Ancestors Queryset Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Retrieves a queryset of ancestor nodes, ordered from parent to root. Supports filtering by depth and including the node itself. ```python obj.get_ancestors_queryset(include_self=True, depth=None) ``` -------------------------------- ### Configure Admin for Tree Model Source: https://github.com/timurkady/django-fast-treenode/blob/main/README.md Set up the admin interface for your tree model using TreenodeModelAdmin in admin.py. Configure list_display and search_fields as needed. ```python from django.contrib import admin from treenode.admin import TreenodeModelAdmin from .models import MyTree @admin.register(MyTree) class MyTreeAdmin(TreenodeModelAdmin): list_display = ("name",) search_fields = ("name",) ``` -------------------------------- ### Get Parent Node Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Retrieves the parent node of the current node. ```python obj.get_parent() ``` -------------------------------- ### Create a Node via API Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/apifirst.md Use a POST request to the API endpoint to create a new node. Include the node's name, parent ID, and priority in the JSON payload. ```bash POST treenode/api/category/ { "name": "New Node", "parent_id": 123, "priority": 0 } ``` -------------------------------- ### Get Children Count Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Returns the total number of direct children for a node. ```python obj.get_children_count() ``` -------------------------------- ### Create Migrations for Application Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/migration.md Generate new database migrations for your application after upgrading the package. Django will detect changes like field renames and model deletions. ```bash python manage.py makemigrations your_app ``` -------------------------------- ### Using SortingChoices for Descending Order Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/models.md Set the 'sorting_direction' class attribute using constants from the SortingChoices class to control the default sorting order of siblings. This example sets it to descending order. ```python class Category(TreeNodeModel): sorting_direction = SortingChoices.DESC ``` -------------------------------- ### Add 'treenode' to INSTALLED_APPS Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/installation.md Register the 'treenode' app in your Django project's settings.py file to enable its functionality. ```python INSTALLED_APPS = [ ... 'treenode', ... ] ``` -------------------------------- ### get_level Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Returns the level of the current node in the tree, starting from 1 for root nodes. ```APIDOC ## get_level ### Description Returns the level of the current node in the tree, starting from 1 for root nodes. ### Method N/A (Instance Method) ### Endpoint N/A ### Parameters None ### Request Example None ### Response #### Success Response - **level** (int) - The level of the node (1-indexed). ``` -------------------------------- ### Access descendants count Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Get the total number of descendants for a node. The current node itself is not counted. ```python obj.descendants_count ``` -------------------------------- ### Load Tree from Data Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Loads a tree structure from a list of dictionaries. Existing records are updated, and new ones are created. Each dictionary must contain an 'id' key. ```python cls.load_tree(tree_data) ``` -------------------------------- ### Get Root Nodes Queryset Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Returns a Django queryset containing all root nodes in the tree. ```python cls.get_roots_queryset() ``` -------------------------------- ### Apply Database Migrations Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/migration.md Apply the generated migrations to update the database schema. This step ensures the database structure aligns with the new model changes. ```bash python manage.py migrate ``` -------------------------------- ### Children Methods Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Manage direct child nodes, including adding new children in specific positions and retrieving child querysets. ```APIDOC ## add_child ### Description Adds a new child node to the current node. The child can be created from keyword arguments or by providing an existing model instance. ### Method INSTANCE METHOD ### Parameters - **position** (str or int) - Optional - Specifies the order position: 'first-child', 'last-child', 'sorted-child', or an integer index. - **instance** (TreeNodeModel) - Optional - An existing, unsaved model instance to add as a child. - **kwargs** - Optional - Keyword arguments for creating a new child node (passed to the inherited node model). ### Request Example ```python obj.add_child(position='first-child', instance=new_node) obj.add_child(name='New Child', position='last-child') ``` ### Response - **created_node** (TreeNodeModel) - The newly created and saved child node object. ``` ```APIDOC ## get_children_queryset ### Description Returns a Django QuerySet containing all direct child nodes of the current node. ### Method INSTANCE METHOD ### Parameters None ### Request Example ```python obj.get_children_queryset() ``` ### Response - **queryset** (QuerySet) - A Django QuerySet of direct child nodes. ``` -------------------------------- ### Access node order (materialized path) Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Retrieve the materialized path string for the current node. This represents its position in the hierarchy. ```python obj.order ``` -------------------------------- ### Add Login and Logout Views to URLs Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/apifirst.md Add these standard login and logout endpoints to your project's urls.py using Django's built-in authentication views. ```python from django.contrib.auth import views as auth_views urlpatterns = [ path('accounts/login/', auth_views.LoginView.as_view(), name='login'), path('accounts/logout/', auth_views.LogoutView.as_view(), name='logout'), ] ``` -------------------------------- ### load_tree Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Loads a tree structure from a list of dictionaries into the database. Existing records are updated, and new ones are created. Each dictionary must include an 'id' key. ```APIDOC ## load_tree ### Description Loads a tree structure from a list of dictionaries into the database. Existing records are updated, and new ones are created. Each dictionary must contain the `id` key. ### Method Class Method ### Endpoint N/A (Class Method) ### Parameters - **tree_data** (list of dict) - A list where each dictionary represents a node and must contain an 'id' key. ### Request Example ```python # Assuming 'YourTreeNodeModel' is your model class tree_data_to_load = [ {'id': 1, 'name': 'Root 1', 'parent_id': None}, {'id': 2, 'name': 'Child 1.1', 'parent_id': 1}, ] YourTreeNodeModel.load_tree(tree_data_to_load) ``` ### Response This method performs database operations and does not return a value. ``` -------------------------------- ### Set Global Cache Limit Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/cache.md Configure the maximum cache size in MB for all TreeNodeModel instances by setting TREENODE_CACHE_LIMIT in settings.py. The default is 100MB. ```python TREENODE_CACHE_LIMIT = 100 ``` -------------------------------- ### Calculate Shortest Path Between Nodes Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Calculates and returns the shortest path between two nodes as a list of primary keys, traversing up to the LCA and then down to the destination. ```python cls.shortest_path(source, destination) ``` -------------------------------- ### get_depth Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Calculates and returns the depth of the current node in the tree, starting from 0 for root nodes. ```APIDOC ## get_depth ### Description Calculates and returns the depth of the current node in the tree, starting from 0 for root nodes. ### Method N/A (Instance Method) ### Endpoint N/A ### Parameters None ### Request Example None ### Response #### Success Response - **depth** (int) - The depth of the node (0-indexed). ``` -------------------------------- ### Configure URL for Secured Tree API Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/customization.md Register the secured API endpoints in your `urls.py`. This ensures that all requests to these endpoints are subject to the permissions defined in the `SecuredTreeAPI` class. ```python from django.urls import path from .views import SecuredTreeAPI urlpatterns = [ *SecuredTreeAPI().discover(), ] ``` -------------------------------- ### Access siblings count Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Get the total number of sibling nodes. This count excludes the current node. ```python obj.siblings_count ``` -------------------------------- ### Get Node Priority Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Returns the ordinal position of a node within its parent's list of children. ```python obj.get_priority() ``` -------------------------------- ### Display Specific Import Errors Source: https://github.com/timurkady/django-fast-treenode/blob/main/treenode/templates/treenode/admin/treenode_import_export.html Iterates through and displays a list of specific errors encountered during an import operation. ```html {% if errors %} {% for error in errors %}* {{ error }} {% endfor %} {% endif %} ``` -------------------------------- ### Get Node Index in Children Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Returns the index of the node within its parent's list of children. ```python obj.get_index() ``` -------------------------------- ### Enable API Security with TREENODE_API_LOGIN_REQUIRED Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/installation.md Globally enable authentication for all tree model APIs. This setting defaults to False. ```python TREENODE_API_LOGIN_REQUIRED = True ``` -------------------------------- ### Create Custom TreeNodeManager with a Custom Method Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/models.md Create a custom model manager by extending TreeNodeModelManager. Add custom methods like 'active' to filter nodes. ```python from treenode.managers import TreeNodeModelManager class CustomTreeNodeManager(TreeNodeModelManager): def active(self): """Return only active nodes.""" return self.get_queryset().filter(is_active=True) ``` -------------------------------- ### clone_subtree Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Clones the current node and its entire subtree, placing the clone under a specified parent. Returns the new root of the cloned subtree. ```APIDOC ## clone_subtree ### Description Clones the current node and its entire subtree under a given parent. Returns the new root of the cloned subtree. ### Method Instance Method ### Endpoint N/A (Instance Method) ### Parameters - **parent** (object, optional) - The parent node under which to clone the subtree. If `None`, the clone will be a root node. ### Request Example ```python # Assuming 'node' is an existing node object and 'new_parent' is another node object cloned_node = node.clone_subtree(parent=new_parent) # Clone as a root node cloned_root = node.clone_subtree() ``` ### Response #### Success Response - **new_root** (object) - The newly created root node of the cloned subtree. ``` -------------------------------- ### Access children count Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Get the total number of direct children for a node. This property offers a quick count. ```python obj.children_count ``` -------------------------------- ### Bulk Update Priorities for Sorting Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/customization.md Update node priorities in bulk to implement custom sorting logic. This approach leverages the framework's efficient background updates. ```python cls.objects.bulk_update(update, fields=['priority']) ``` -------------------------------- ### Get Previous Sibling Node Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Returns the previous sibling node in the tree, or None if no previous sibling exists. ```python obj.get_previous_sibling() ``` -------------------------------- ### move_to Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Moves the model instance relative to a target node and sets its position. The position options are detailed in the `insert_at` method. ```APIDOC ## move_to ### Description Moves the model instance relative to the target node and sets its position (if necessary). ### Method Signature ```python obj.move_to(target, position=0) ``` ### Parameters #### Target Node - **target**: The target node relative to which this node will be placed. #### Position - **position** (integer or string) - Optional - The position relative to the target node. For details, see the `insert_at` method's position parameter. ``` -------------------------------- ### get_tree Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Returns an n-dimensional dictionary representing the model tree. If an instance is provided, it returns the subtree rooted at that instance. ```APIDOC ## get_tree ### Description Returns an n-dimensional dictionary representing the model tree. If an instance is passed, it returns a subtree rooted at that instance. ### Method Class Method ### Endpoint N/A (Class Method) ### Parameters - **instance** (object, optional) - The root instance of the subtree to retrieve. If `None`, the entire tree is returned. ### Request Example ```python # Assuming 'YourTreeNodeModel' is your model class # Get the entire tree tree_dict = YourTreeNodeModel.get_tree() # Get a specific subtree # Assuming 'root_instance' is a specific node object subtree_dict = YourTreeNodeModel.get_tree(instance=root_instance) ``` ### Response #### Success Response - **tree_representation** (dict) - A nested dictionary representing the tree structure. ``` -------------------------------- ### Get Last Root Node Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Retrieves the last root node in the tree. Returns None if the tree is empty. ```python cls.get_last_root() ``` -------------------------------- ### Extend TreeNodeModel with Custom Fields and Methods Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/models.md Extend TreeNodeModel to add custom fields like 'name' and 'code', and methods like 'get_full_string'. Ensure to inherit Meta class from TreeNodeModel.Meta. ```python from django.db import models from treenode.models import TreeNodeModel from treenode.choices import SortingChoices class Category(TreeNodeModel): treenode_display_field = "name" sorting_field = "name" sorting_direction = SortingChoices.DESC name = models.CharField(max_length=50) code = models.CharField(max_length=5) class Meta(TreeNodeModel.Meta): verbose_name = "Category" verbose_name_plural = "Categories" def get_full_string(self): return f"{self.code} - {self.name}" ``` -------------------------------- ### Get Node Order Value Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Retrieves the order value associated with the node, used for maintaining tree ordering. ```python obj.get_order() ``` -------------------------------- ### shortest_path Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Calculates and returns the shortest path between two nodes as a list of primary keys. ```APIDOC ## shortest_path ### Description Calculates and returns the shortest path between two nodes as a list of primary keys. ### Method N/A (Class Method) ### Endpoint N/A ### Parameters #### Path Parameters - **source** (node object) - Required - The starting node for the path. - **destination** (node object) - Required - The ending node for the path. ### Response #### Success Response - **path** (list) - A list of primary keys representing the shortest path from source to destination. ``` -------------------------------- ### Get Last Child Node Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Retrieves the last direct child node. Returns None if the node has no children. ```python obj.get_last_child() ``` -------------------------------- ### Load Tree from JSON String Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Decodes a JSON-compatible string into a tree structure, synchronizing with the database. ```python cls.load_tree_json(json_str) ``` -------------------------------- ### get_family_pks Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Returns a list of primary keys for the ancestors, the current node, and all descendants, in tree order. ```APIDOC ## get_family_pks ### Description Returns a list of primary keys for the ancestors, the current node, and all descendants, in tree order. ### Method N/A (Instance Method) ### Endpoint N/A ### Parameters None ### Request Example None ### Response #### Success Response - **family_pks** (list) - A list of integers representing the primary keys of the family nodes. ``` -------------------------------- ### Get Ancestors Count Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Calculates and returns the total number of ancestor nodes, with options to include the node itself and filter by depth. ```python obj.get_ancestors_count(include_self=True, depth=None) ``` -------------------------------- ### List all nodes Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/apifirst.md Retrieves a list of all nodes for a given model, ordered according to the tree structure. Supports a `flat=true` query parameter for a flattened list. ```APIDOC ## GET /api//?flat=true ### Description List all nodes, ordered by tree structure. ### Method GET ### Endpoint `/api//?flat=true` ### Query Parameters - **flat** (boolean) - Optional - If true, returns a flattened list of nodes. ``` -------------------------------- ### Access node level Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Get the level of the current node in the tree. This is often synonymous with depth but can be defined differently based on implementation. ```python obj.level ``` -------------------------------- ### Dynamic Factory Method for TreeNodeForm Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/admin.md Use the dynamic factory method to create TreeNodeForm instances for different tree models, ensuring correct association. ```python CategoryForm = TreeNodeForm.factory(Category) ``` -------------------------------- ### Get First Sibling Node Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Returns the first sibling node in the tree. May return the node itself if it's the leftmost sibling. ```python obj.get_first_sibling() ``` -------------------------------- ### add_root Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Adds a new root node to the tree. It can be positioned explicitly or appended as the last root. Additional keyword arguments are passed for node creation. ```APIDOC ## add_root ### Description Adds a root node to the tree. ### Method Signature ```python cls.add_root(position=None, **kwargs) ``` ### Parameters - **position** (string or integer) - Optional - Specifies the order position. Can be `'first-root'`, `'last-root'`, `'sorted-root'`, or an integer value. - **kwargs**: Additional keyword arguments for node creation. Alternatively, an unsaved model instance can be passed using the `instance` keyword. ### Returns Returns the created and saved node object. ``` -------------------------------- ### Get Descendants Count Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Returns the total count of descendant nodes. Options to include the self node and limit depth are available. ```python obj.get_descendants_count(include_self=False, depth=None) ``` -------------------------------- ### Clone Subtree Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Clones the current node and its entire subtree under a specified parent. Returns the new root of the cloned subtree. ```python obj.clone_subtree(parent=None) ``` -------------------------------- ### load_tree_json Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Decodes a JSON-compatible string and loads the tree structure into the database. This method synchronizes existing and creates new records. ```APIDOC ## load_tree_json ### Description Takes a JSON-compatible string and decodes it into a tree structure, loading it into the database. Existing records are updated, and new ones are created. ### Method Class Method ### Endpoint N/A (Class Method) ### Parameters - **json_str** (string) - A JSON string representing the tree structure. ### Request Example ```python # Assuming 'YourTreeNodeModel' is your model class tree_json_string = '[{"id": 1, "name": "Root A"}, {"id": 2, "name": "Child A.1", "parent_id": 1}]' YourTreeNodeModel.load_tree_json(tree_json_string) ``` ### Response This method performs database operations and does not return a value. ``` -------------------------------- ### Admin Base Site Template Extension Source: https://github.com/timurkady/django-fast-treenode/blob/main/treenode/templates/treenode/admin/treenode_import_export.html Extends the base admin site template to include custom styles and content for the treenode import/export page. ```html {% extends "admin/base\_site.html" %} {% load static %} {% block extrastyle %} {{ block.super }} {# Load built-in admin form styles #} {% endblock %} {% block content %} ``` -------------------------------- ### Include TreeWidget JavaScript and CSS Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/admin.md Ensure necessary JavaScript and CSS files are included when using TreeWidget in non-admin Django templates. ```html ``` -------------------------------- ### Access node index Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Get the index of the current node within its parent's children list. This indicates its position among siblings. ```python obj.index ``` -------------------------------- ### Access ancestor count Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Get the total number of ancestors for a node. This property offers a quick count without retrieving the ancestor list. ```python obj.ancestors_count ``` -------------------------------- ### Basic Category Model Inheritance Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/models.md Inherit from TreeNodeModel to create a custom tree model. Specify 'treenode_display_field' for admin panel display. Ensure to inherit from TreeNodeModel.Meta in your model's Meta class. ```python from django.db import models from treenode.models import TreeNodeModel class Category(TreeNodeModel): treenode_display_field = "name" # Defines the field used for display in the admin panel name = models.CharField(max_length=50) class Meta(TreeNodeModel.Meta): # Preserve TreeNodeModel's indexing settings verbose_name = "Category" verbose_name_plural = "Categories" ``` -------------------------------- ### get_children_pks Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Returns a list of primary keys for all direct children of the current node. ```APIDOC ## get_children_pks ### Description Returns a list of primary keys for all direct children of the current node. ### Method N/A (Instance Method) ### Endpoint N/A ### Parameters None ### Request Example None ### Response #### Success Response - **children_pks** (list) - A list of integers representing the primary keys of the children nodes. ``` -------------------------------- ### Get Common Ancestor Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Finds the lowest common ancestor between the current node and a target node. Returns a list of primary key objects. ```python obj.get_common_ancestor(target) ``` -------------------------------- ### Ancestor Methods Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Retrieve and manipulate ancestor nodes, with options for filtering by depth, retrieving primary keys, and counting. ```APIDOC ## get_ancestors_queryset ### Description Returns the ancestors queryset, ordered from parent to root. ### Method INSTANCE METHOD ### Parameters - **include_self** (bool) - Optional - Whether to include the current node in the queryset. - **depth** (int) - Optional - The maximum depth of ancestors to retrieve. ### Request Example ```python obj.get_ancestors_queryset(include_self=True, depth=None) ``` ### Response - **queryset** (QuerySet) - A Django QuerySet of ancestor nodes. ``` ```APIDOC ## get_ancestors_pks ### Description Returns a list of primary keys (pks) for all ancestor nodes. ### Method INSTANCE METHOD ### Parameters - **include_self** (bool) - Optional - Whether to include the current node's pk. - **depth** (int) - Optional - The maximum depth of ancestors to retrieve. ### Request Example ```python obj.get_ancestors_pks(include_self=True, depth=None) ``` ### Response - **pks** (list) - A list of primary keys of ancestor nodes. ``` ```APIDOC ## get_ancestors ### Description Returns a list of all ancestor nodes, ordered from root to parent. ### Method INSTANCE METHOD ### Parameters - **include_self** (bool) - Optional - Whether to include the current node in the list. - **depth** (int) - Optional - The maximum depth of ancestors to retrieve. ### Request Example ```python obj.get_ancestors(include_self=True, depth=None) ``` ### Response - **ancestors** (list) - A list of ancestor node objects. ``` ```APIDOC ## get_ancestors_count ### Description Returns the total count of ancestor nodes. ### Method INSTANCE METHOD ### Parameters - **include_self** (bool) - Optional - Whether to include the current node in the count. - **depth** (int) - Optional - The maximum depth of ancestors to count. ### Request Example ```python obj.get_ancestors_count(include_self=True, depth=None) ``` ### Response - **count** (int) - The number of ancestor nodes. ``` ```APIDOC ## get_common_ancestor ### Description Finds the lowest common ancestor between the current node and a target node. ### Method INSTANCE METHOD ### Parameters - **target** (TreeNodeModel) - Required - The other node to find the common ancestor with. ### Request Example ```python obj.get_common_ancestor(target_node) ``` ### Response - **common_ancestor** (TreeNodeModel) - The lowest common ancestor node. ``` -------------------------------- ### Retrieve the entire tree Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/apifirst.md Retrieves the complete tree structure for a given model. Supports a `flat=true` query parameter for a flattened list. ```APIDOC ## GET /api//tree/?flat=true ### Description Retrieve the entire tree. ### Method GET ### Endpoint `/api//tree/` ### Query Parameters - **flat** (boolean) - Optional - If true, returns a flattened list of nodes. ``` -------------------------------- ### Get Value from Cache Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/cache.md Retrieve a cached value using treenode_cache.get() with the cache key. If the value is not found (returns None), compute it and then set it in the cache. ```python cached_value = treenode_cache.get(cache_key) if cached_value is None: cached_value = compute_expensive_query() treenode_cache.set(cache_key, cached_value) ``` -------------------------------- ### Integrate Custom API URL with AutoTreeAPI Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/customization.md Manually add URLs for custom API views alongside the auto-generated endpoints. This ensures custom actions are accessible without interfering with the standard API structure. ```python from django.urls import path from treenode.views.autoapi import AutoTreeAPI from .views import CategoryFlatDescendantsAPI urlpatterns = [ *AutoTreeAPI().discover(), # This is important! path( 'api/category//descendants-flat/', CategoryFlatDescendantsAPI.as_view(), name='category-flat-descendants' ), ] ``` -------------------------------- ### Retrieve the tree with depth annotations Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/apifirst.md Retrieves the tree structure with depth annotations for each node. This provides information about the level of each node in the hierarchy. ```APIDOC ## GET /api//tree/?annotated=true ### Description Retrieve the tree with depth annotations. ### Method GET ### Endpoint `/api//tree/` ### Query Parameters - **annotated** (boolean) - Optional - If true, returns the tree with depth annotations. ``` -------------------------------- ### insert_at Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Inserts a node into the tree relative to a target node. It supports various positions like 'first-child', 'last-child', 'left-sibling', etc., and can optionally save the node to the tree. ```APIDOC ## insert_at ### Description Insert a node into the tree relative to the target node. ### Method Signature ```python obj.insert_at(target, position='first-child', save=False) ``` ### Parameters #### Target Node - **target**: The target node relative to which this node will be placed. #### Position - **position** (string) - Optional - The position relative to the target node. Can be one of: - `first-root`: The node will be the first root node. - `last-root`: The node will be the last root node. - `sorted-root`: The new node will be moved after sorting by the treenode_sort_field field. - `first-sibling`: The node will be the new leftmost sibling of the target node. - `left-sibling`: The node will take the target node’s place, which will be moved to the target position with shifting follows nodes. - `right-sibling`: The node will be moved to the position after the target node. - `last-sibling`: The node will be the new rightmost sibling of the target node. - `sorted-sibling`: The new node will be moved after sorting by the treenode_sort_field field. - `first-child`: The node will be the first child of the target node. - `last-child`: The node will be the new rightmost child of the target. - `sorted-child`: The new node will be moved after sorting by the treenode_sort_field field. #### Save Option - **save** (boolean) - Optional - If `true`, the node will be saved in the tree. Otherwise, the method will return a model instance with updated fields. ``` -------------------------------- ### Custom Sorting Field for Category Model Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/models.md Customize the field used for sorting sibling nodes by setting the 'sorting_field' class attribute. This example uses the 'name' field for alphabetical sorting. ```python class Category(TreeNodeModel): sorting_field = "name" ... ``` -------------------------------- ### Access descendants primary keys Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Retrieve a list of primary keys for all descendants of the current node. The current node itself is not included. ```python obj.descendants_pks ``` -------------------------------- ### Display Import/Export Results Source: https://github.com/timurkady/django-fast-treenode/blob/main/treenode/templates/treenode/admin/treenode_import_export.html Conditionally displays the results of an import operation, including counts of created, updated items, and any errors encountered. ```html {% if errors or created_count or updated_count %} {% if created_count %}* Successfully created: {{ created_count }}{% endif %} {% if updated_count %}* Successfully updated: {{ updated_count }}{% endif %} {% if errors %}* Errors: {{ errors|length }}{% endif %} {% endif %} ``` -------------------------------- ### Update Tree Structure Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Manually rebuilds the tree structure in the database. ```python cls.update_tree() ``` -------------------------------- ### Access siblings primary keys Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Retrieve a list of primary keys for all sibling nodes. This count excludes the current node. ```python obj.siblings_pks ``` -------------------------------- ### Category Selection Form with TreeWidget Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/admin.md Implement a form using TreeWidget for hierarchical selection of parent nodes. This widget requires jQuery and can dynamically fetch data. ```python from django import forms from treenode.widgets import TreeWidget from .models import Category class CategorySelectionForm(forms.Form): parent = forms.ModelChoiceField( queryset=Category.objects.all(), widget=TreeWidget(), required=False ) ``` -------------------------------- ### Create a new node Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/apifirst.md Creates a new node within the tree structure for a given model. Requires a request body with node details. ```APIDOC ## POST /api// ### Description Create a new node. ### Method POST ### Endpoint `/api//` ### Request Body - **name** (string) - Required - The name of the new node. - **parent_id** (integer) - Optional - The ID of the parent node. If not provided, the node becomes a root node. - **priority** (integer) - Optional - The priority of the node within its parent. ### Request Example ```json { "name": "New Node", "parent_id": 123, "priority": 0 } ``` ``` -------------------------------- ### Access ancestor primary keys Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Retrieve a list of primary keys for all ancestors, including the node itself. Useful for database operations. ```python obj.ancestors_pks ``` -------------------------------- ### get_first_child Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Retrieves the first direct child node, or None if no children exist. ```APIDOC ## get_first_child ### Description Retrieves the first direct child node, or None if no children exist. ### Method N/A (Instance Method) ### Endpoint N/A ### Parameters None ### Request Example None ### Response #### Success Response - **first_child** (node object or None) - The first child node object, or None if the node has no children. ``` -------------------------------- ### get_descendants_pks Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Returns a list of primary keys for all descendant nodes, optionally including the current node and filtering by depth. ```APIDOC ## get_descendants_pks ### Description Returns a list of primary keys for all descendant nodes, optionally including the current node and filtering by depth. ### Method N/A (Instance Method) ### Endpoint N/A ### Parameters #### Query Parameters - **include_self** (bool) - Optional - If True, includes the current node's primary key in the list. - **depth** (int) - Optional - The maximum depth to retrieve descendant primary keys from. If None, all descendants are included. ``` -------------------------------- ### Define a Tree Model Source: https://github.com/timurkady/django-fast-treenode/blob/main/README.md Create a custom tree model by inheriting from TreenodeModel in your models.py. Define a display_field for representation. ```python from treenode.models import TreenodeModel class MyTree(TreenodeModel): name = models.CharField(max_length=255) display_field = "name" ``` -------------------------------- ### Access root node primary key Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Retrieve the primary key of the root node for the current node's tree. Returns the node's own PK if it is a root. ```python obj.root_pk ``` -------------------------------- ### Access children primary keys Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Retrieve a list of primary keys for all direct children of the current node. Useful for database operations. ```python obj.children_pks ``` -------------------------------- ### get_first_root Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Retrieves the first root node in the tree. Returns `None` if the tree is empty. ```APIDOC ## get_first_root ### Description Returns the first root node in the tree or `None` if it is empty. ### Method This is a class method. ### Endpoint N/A (Class Method) ### Parameters None ### Request Example ```python # Assuming 'YourTreeNodeModel' is your model class first_root = YourTreeNodeModel.get_first_root() ``` ### Response #### Success Response - **node** (object or None) - The first root node object, or `None` if the tree is empty. ``` -------------------------------- ### Replace a node completely Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/apifirst.md Replaces an existing node entirely with new data. Requires a full request body with all node fields. ```APIDOC ## PUT /api/// ### Description Replace a node completely. ### Method PUT ### Endpoint `/api///` ### Parameters #### Path Parameters - **id** (integer) - Required - The ID of the node to replace. ### Request Body - **name** (string) - Required - The name of the node. - **parent_id** (integer) - Optional - The ID of the parent node. - **priority** (integer) - Optional - The priority of the node. ``` -------------------------------- ### get_root_pk Source: https://github.com/timurkady/django-fast-treenode/blob/main/docs/api.md Returns the primary key (PK) of the root node for the current node. ```APIDOC ## get_root_pk ### Description Returns the root node pk for the current node. ### Method Signature ```python obj.get_root_pk() ``` ```