Fix tree fields not being available after Model.objects.create() with with_tree_fields=True
When using TreeQuerySet.as_manager(with_tree_fields=True), tree fields (tree_depth, tree_path, tree_ordering) were not available on instances returned by Model.objects.create(), forcing users to perform an additional database query to access these fields.
Problem
class Node(TreeNode):
name = models.CharField(max_length=100)
objects = TreeQuerySet.as_manager(with_tree_fields=True)
# Before this fix:
root = Node.objects.create(name="Root")
print(root.tree_depth) # AttributeError: 'Node' object has no attribute 'tree_depth'
# Users had to do this workaround:
root = Node.objects.get(pk=root.pk) # Extra query needed
print(root.tree_depth) # 0
Solution
Now tree fields are automatically available after create() when with_tree_fields=True:
# After this fix:
root = Node.objects.create(name="Root")
print(root.tree_depth) # 0
print(root.tree_path) # [root.pk]
child = Node.objects.create(name="Child", parent=root)
print(child.tree_depth) # 1
print(len(child.tree_path)) # 2
Implementation
-
Modified
TreeManager.create(): Re-queries the created instance with tree fields whenwith_tree_fields=True -
Added
TreeManager.bulk_create(): Documents that bulk operations don't return tree fields (expected behavior for performance) - Performance optimized: Only performs the extra query when tree fields are actually needed
Documentation
Added comprehensive documentation to README.rst explaining:
- New
create()behavior with examples -
bulk_create()limitations -
refresh_from_db()behavior and workarounds
Backward Compatibility
No breaking changes - existing code continues to work exactly as before. The fix only affects models using with_tree_fields=True and provides the intuitive behavior users expect.
Fixes #40.
[!WARNING]
Firewall rules blocked me from connecting to one or more addresses (expand for details)
I tried to connect to the following addresses, but was blocked by firewall rules:
esm.ubuntu.com
- Triggering command:
/usr/lib/apt/methods/https(dns block)If you need me to access, download, or install something from one of these locations, you can either:
- Configure Actions setup steps to set up my environment, which run before the firewall is enabled
- Add the appropriate URLs or hosts to the custom allowlist in this repository's Copilot coding agent settings (admins only)
✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.