diff --git a/django/db/models/sql/compiler.py b/django/db/models/sql/compiler.py index 839e37aa8a..72a6537e05 100644 --- a/django/db/models/sql/compiler.py +++ b/django/db/models/sql/compiler.py @@ -559,7 +559,9 @@ class SQLCompiler: # to exclude extraneous selects. sub_selects = [] sub_params = [] - for select, _, alias in self.select: + for index, (select, _, alias) in enumerate(self.select, start=1): + if not alias and with_col_aliases: + alias = 'col%d' % index if alias: sub_selects.append("%s.%s" % ( self.connection.ops.quote_name('subquery'), @@ -573,7 +575,7 @@ class SQLCompiler: return 'SELECT %s FROM (%s) subquery' % ( ', '.join(sub_selects), ' '.join(result), - ), sub_params + params + ), tuple(sub_params + params) return ' '.join(result), tuple(params) finally: diff --git a/docs/releases/2.0.3.txt b/docs/releases/2.0.3.txt index 50b39653ea..4fbca2e247 100644 --- a/docs/releases/2.0.3.txt +++ b/docs/releases/2.0.3.txt @@ -9,4 +9,5 @@ Django 2.0.3 fixes several bugs in 2.0.2. Bugfixes ======== -* ... +* Fixed a regression that caused sliced ``QuerySet.distinct().order_by()`` + followed by ``count()`` to crash (:ticket:`29108`). diff --git a/tests/queries/tests.py b/tests/queries/tests.py index 668b07361a..79bd8203ca 100644 --- a/tests/queries/tests.py +++ b/tests/queries/tests.py @@ -1891,6 +1891,9 @@ class Queries6Tests(TestCase): qs = Tag.objects.exclude(category=None).exclude(category__name='foo') self.assertEqual(str(qs.query).count(' INNER JOIN '), 1) + def test_distinct_ordered_sliced_subquery_aggregation(self): + self.assertEqual(Tag.objects.distinct().order_by('category__name')[:3].count(), 3) + class RawQueriesTests(TestCase): def setUp(self):