Enable tree fields in .values() and .values_list() calls
This PR enables tree fields (tree_depth, tree_path, tree_ordering, and custom tree fields) to be included in .values() and .values_list() calls while maintaining full backward compatibility.
Problem
Previously, tree fields were excluded from .values() calls even when explicitly requested:
# This would not include tree_depth in the result
Node.objects.with_tree_fields().values('name', 'tree_depth')
# Users had to resort to RawSQL workarounds
Node.objects.with_tree_fields().values(
tree_depth=RawSQL("tree_depth", ()),
tree_path=RawSQL("tree_path", ()),
)
Solution
Modified the TreeCompiler.as_sql() method to:
- Check if tree fields are specifically requested in the
.values()call - Only include tree fields that were explicitly requested
- Maintain existing behavior for all other cases
New Functionality
# ✅ Now works - include specific tree fields
Node.objects.with_tree_fields().values('tree_depth')
Node.objects.with_tree_fields().values('name', 'tree_depth', 'tree_path')
Node.objects.with_tree_fields().values_list('tree_depth', flat=True)
# ✅ Works with custom tree fields too
Node.objects.tree_fields(tree_names="name").values('name', 'tree_names')
Backward Compatibility
All existing behavior is preserved:
# Still excludes tree fields (unchanged behavior)
Node.objects.with_tree_fields().values('name')
Node.objects.with_tree_fields().values()
# Still includes all tree fields (unchanged behavior)
Node.objects.with_tree_fields()
# RawSQL workaround continues to work
Node.objects.with_tree_fields().values(tree_depth=RawSQL("tree_depth", ()))
Implementation Details
The fix required only a 6-line change in TreeCompiler.as_sql():
- Changed the condition from
elif self.query.values_select:toelif self.query.values_select is not None: - Added filtering logic to include only requested tree fields when using
.values() - Comprehensive test suite added covering all scenarios and edge cases
This change works with all supported database backends (PostgreSQL, MySQL, SQLite) since it leverages the existing CTE infrastructure without modification.
Fixes #69.
💡 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.