Skip to content

Commit

Permalink
Test the behavior of .descendants() queries
Browse files Browse the repository at this point in the history
  • Loading branch information
matthiask committed Aug 18, 2024
1 parent 2e01ba1 commit 73ee469
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 2 deletions.
4 changes: 3 additions & 1 deletion CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ Change log
Next version
~~~~~~~~~~~~

- Added Django 5.1b1 to the testsuite.
- Added Django 5.1 to the testsuite.
- Added tests showing that ``.descendants().update(...)`` doesn't work, but
``.filter(pk__in=....descendants()).update(...)`` does.


0.19 (2024-04-25)
Expand Down
49 changes: 49 additions & 0 deletions tests/testapp/test_queries.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from django.db import connections, models
from django.db.models import Count, Q, Sum
from django.db.models.expressions import RawSQL
from django.db.utils import OperationalError
from django.test import TestCase, override_settings

from testapp.models import (
Expand Down Expand Up @@ -159,6 +160,54 @@ def test_update_aggregate(self):
# known yet.
)

def test_update_descendants(self):
"""UpdateQuery does not work with tree queries"""
tree = self.create_tree()
with self.assertRaises(OperationalError) as cm:
tree.root.descendants().update(name="test")
self.assertIn("__tree.tree_path", str(cm.exception))

def test_update_descendants_with_filter(self):
"""Updating works when using a filter"""
tree = self.create_tree()
Model.objects.filter(pk__in=tree.child2.descendants()).update(name="test")
self.assertEqual(
[node.name for node in Model.objects.with_tree_fields()],
[
"root",
"1",
"1-1",
"2",
"test",
"test",
],
)

def test_delete_descendants(self):
"""DeleteQuery works with tree queries"""
tree = self.create_tree()
tree.child2.descendants(include_self=True).delete()

self.assertEqual(
list(Model.objects.with_tree_fields()),
[
tree.root,
tree.child1,
tree.child1_1,
# tree.child2,
# tree.child2_1,
# tree.child2_2,
],
)

def test_aggregate_descendants(self):
"""AggregateQuery works with tree queries"""
tree = self.create_tree()
self.assertEqual(
tree.root.descendants(include_self=True).aggregate(Sum("pk"))["pk__sum"],
sum(node.pk for node in Model.objects.all()),
)

def test_values(self):
self.create_tree()
self.assertEqual(
Expand Down
2 changes: 1 addition & 1 deletion tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ deps =
dj41: Django>=4.1,<4.2
dj42: Django>=4.2,<5.0
dj50: Django>=5.0,<5.1
dj51: Django>=5.1b1,<5.2
dj51: Django>=5.1,<5.2
djmain: https://github.com/django/django/archive/main.tar.gz
postgresql: psycopg2-binary
mysql: mysqlclient
Expand Down

0 comments on commit 73ee469

Please sign in to comment.