Skip to content

Conversation

Copilot
Copy link

@Copilot Copilot AI commented Sep 24, 2025

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 Copilot AI changed the title [WIP] Tree Fields Not Accurate After Model.objects.create() Fix tree fields not being available after Model.objects.create() with with_tree_fields=True Sep 24, 2025
Copilot finished work on behalf of matthiask September 24, 2025 11:21
@Copilot Copilot AI requested a review from matthiask September 24, 2025 11:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Tree Fields Not Accurate After Model.objects.create()

2 participants