Fix missing space in COUNT(DISTINCT ...) SQL generation

Ensure a space follows DISTINCT to prevent syntax errors
when combining distinct=True with Case expressions in Count.
Adds tests to verify correct SQL is generated.
Fixes query errors on Django 2.2 and all DB backends.
This commit is contained in:
utkarsh.arya@zomato.com 2025-11-15 22:55:00 +00:00
parent 838e432e3e
commit 4d62bc9763
2 changed files with 23 additions and 1 deletions

View file

@ -87,3 +87,25 @@ class FilteredAggregateTests(TestCase):
older_friends_count__gte=2,
)
self.assertEqual(qs.get(pk__in=qs.values('pk')), self.a1)
def test_count_distinct_with_case(self):
"""Test Count with both distinct=True and a Case expression."""
agg = Count(
Case(When(age__gte=40, then=F('age'))),
distinct=True,
)
# This should produce valid SQL with space between DISTINCT and CASE
result = Author.objects.aggregate(count=agg)
# Expected: Count distinct ages >= 40
self.assertIsInstance(result['count'], int)
def test_count_distinct_with_case_and_filter(self):
"""Test Count with distinct=True, Case, and filter together."""
agg = Count(
Case(When(age__gte=40, then=F('age'))),
distinct=True,
filter=Q(name__startswith='test'),
)
# This should produce valid SQL with all three conditions
result = Author.objects.aggregate(count=agg)
self.assertIsInstance(result['count'], int)