Add add_related_count() method as replacement for django-mptt functionality #93
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This PR implements
add_related_count()method forTreeQuerySetas a direct replacement for django-mptt's method of the same name, enabling users to migrate from django-mptt while retaining the ability to count related objects across tree hierarchies.Problem
Users migrating from django-mptt to django-tree-queries were missing the
add_related_count()functionality, which annotates tree nodes with counts of related objects. The challenge was that django-mptt's approach relies on concrete database fields (likelft,rght), while django-tree-queries uses CTE-generated fields liketree_paththat aren't accessible to Django'sSubqueryclass.Solution
The new implementation leverages django-tree-queries' existing CTE infrastructure and
tree_pathfield to provide the same functionality:Key Features
ANY(__tree.tree_path)), with fallback string operations for SQLite, MySQL, and MariaDBtree_pathfield from recursive Common Table ExpressionsImplementation Details
The method works by:
Count()with reverse relationshipstree_pathto find all descendants of each node, then counting related objects across the entire subtreeTesting
Added comprehensive test coverage including:
RegionandSite) that mirror real-world usage scenariosDocumentation
Updated README.rst with:
This provides a complete migration path for django-mptt users who rely on
add_related_count()functionality.Fixes #21.
💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.