django-tree-queries icon indicating copy to clipboard operation
django-tree-queries copied to clipboard

Fix tree fields not being available after Model.objects.create() with with_tree_fields=True

Open Copilot opened this issue 5 months ago • 0 comments

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 when with_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:


✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

Copilot avatar Sep 24 '25 11:09 Copilot