Skip to content

Commit

Permalink
Handle tree queryset .values() even more correctly
Browse files Browse the repository at this point in the history
  • Loading branch information
glennmatthews committed Nov 29, 2023
1 parent 1fd6d1f commit bb4b4d2
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
21 changes: 21 additions & 0 deletions tests/testapp/test_queries.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,20 @@ def test_update_aggregate(self):
)

def test_values(self):
tree = self.create_tree()
self.assertEqual(
list(Model.objects.with_tree_fields().values("name")),
[
{"name": "root"},
{"name": "1"},
{"name": "1-1"},
{"name": "2"},
{"name": "2-1"},
{"name": "2-2"},
],
)

def test_values_ancestors(self):
tree = self.create_tree()
self.assertEqual(
list(Model.objects.ancestors(tree.child2_1).values()),
Expand All @@ -169,6 +183,13 @@ def test_values(self):
)

def test_values_list(self):
tree = self.create_tree()
self.assertEqual(
list(Model.objects.with_tree_fields().values_list("name", flat=True)),
["root", "1", "1-1", "2", "2-1", "2-2"],
)

def test_values_list_ancestors(self):
tree = self.create_tree()
self.assertEqual(
list(
Expand Down
5 changes: 2 additions & 3 deletions tree_queries/compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,6 @@ def as_sql(self, *args, **kwargs):
# problem but I just gotta stop worrying and trust the testsuite.
skip_tree_fields = (
(self.query.distinct and self.query.subquery)
or self.query.values_select
or any( # pragma: no branch
# OK if generator is not consumed completely
annotation.is_summary
Expand Down Expand Up @@ -244,9 +243,9 @@ def as_sql(self, *args, **kwargs):

self.query.add_extra(
# Do not add extra fields to the select statement when it is a
# summary query
# summary query or when using .values() or .values_list()
select={}
if skip_tree_fields
if skip_tree_fields or self.query.values_select
else {
"tree_depth": "__tree.tree_depth",
"tree_path": "__tree.tree_path",
Expand Down

0 comments on commit bb4b4d2

Please sign in to comment.