Skip to content

Commit 9257e6b

Browse files
author
simwr872
committed
add annotation if 5.2 selected
1 parent 948ec03 commit 9257e6b

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

django_cte/cte.py

+9
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,15 @@ def queryset(self):
112112
if cte_query.values_select:
113113
query.set_values(cte_query.values_select)
114114
qs._iterable_class = ValuesIterable
115+
if django.VERSION >= (5, 2):
116+
for alias in cte_query.values_select:
117+
if (
118+
alias not in cte_query.annotations
119+
and cte_query.has_select_fields
120+
and alias in cte_query.selected
121+
):
122+
col = CTEColumnRef(alias, self.name, cte_query.resolve_ref(alias).output_field)
123+
query.add_annotation(col, alias)
115124
if cte_query.annotations:
116125
for alias, value in cte_query.annotations.items():
117126
col = CTEColumnRef(alias, self.name, value.output_field)

tests/test_recursive.py

+15
Original file line numberDiff line numberDiff line change
@@ -318,3 +318,18 @@ def make_regions_cte(cte):
318318
self.assertTrue(
319319
str(query.query).startswith('WITH RECURSIVE "cte" AS MATERIALIZED')
320320
)
321+
322+
def test_recursive_self_queryset(self):
323+
def make_regions_cte(cte):
324+
return Region.objects.filter(
325+
pk="earth"
326+
).values("pk").union(
327+
cte.join(Region, parent=cte.col.pk).values("pk")
328+
)
329+
cte = With.recursive(make_regions_cte)
330+
queryset = cte.queryset().with_cte(cte).order_by("pk")
331+
print(queryset.query)
332+
self.assertEqual(list(queryset), [
333+
{'pk': 'earth'},
334+
{'pk': 'moon'},
335+
])

0 commit comments

Comments
 (0)