diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py index 6f883031ef..1a86266e6c 100644 --- a/django/db/models/sql/query.py +++ b/django/db/models/sql/query.py @@ -472,6 +472,9 @@ class Query(object): def has_results(self, using): q = self.clone() if not q.distinct: + if q.group_by is True: + q.add_fields((f.attname for f in self.model._meta.concrete_fields), False) + q.set_group_by() q.clear_select_clause() q.clear_ordering(True) q.set_limits(high=1) diff --git a/docs/releases/1.8.3.txt b/docs/releases/1.8.3.txt index 09aa2d8fe7..d5bde6040c 100644 --- a/docs/releases/1.8.3.txt +++ b/docs/releases/1.8.3.txt @@ -14,3 +14,6 @@ Bugfixes * Fixed crash during :djadmin:`makemigrations` if a migrations module either is missing ``__init__.py`` or is a file (:ticket:`24848`). + +* Fixed ``exists()`` returning incorrect results after annotation with + ``Count()`` (:ticket:`24835`). diff --git a/tests/annotations/tests.py b/tests/annotations/tests.py index 9e647cd3f9..c08dd84d57 100644 --- a/tests/annotations/tests.py +++ b/tests/annotations/tests.py @@ -245,6 +245,10 @@ class NonAggregateAnnotationTestCase(TestCase): lambda a: (a['age'], a['age_count']) ) + def test_annotate_exists(self): + authors = Author.objects.annotate(c=Count('id')).filter(c__gt=1) + self.assertFalse(authors.exists()) + def test_column_field_ordering(self): """ Test that columns are aligned in the correct order for