diff --git a/django/db/models/query.py b/django/db/models/query.py index 7d41fe1ca6..5969ab128c 100644 --- a/django/db/models/query.py +++ b/django/db/models/query.py @@ -625,7 +625,7 @@ class QuerySet(object): % arg.default_alias) kwargs[arg.default_alias] = arg - names = set([f.name for f in self.model._meta.fields]) + names = set(self.model._meta.get_all_field_names()) for aggregate in kwargs: if aggregate in names: raise ValueError("The %s annotation conflicts with a field on " diff --git a/tests/regressiontests/aggregation_regress/tests.py b/tests/regressiontests/aggregation_regress/tests.py index 786431420d..58d0b2748f 100644 --- a/tests/regressiontests/aggregation_regress/tests.py +++ b/tests/regressiontests/aggregation_regress/tests.py @@ -489,6 +489,14 @@ class AggregationTests(TestCase): # Regression for #11256 - providing an aggregate name that conflicts with a field name on the model raises ValueError self.assertRaises(ValueError, Author.objects.annotate, age=Avg('friends__age')) + def test_m2m_name_conflict(self): + # Regression for #11256 - providing an aggregate name that conflicts with an m2m name on the model raises ValueError + self.assertRaises(ValueError, Author.objects.annotate, friends=Count('friends')) + + def test_reverse_relation_name_conflict(self): + # Regression for #11256 - providing an aggregate name that conflicts with a reverse-related name on the model raises ValueError + self.assertRaises(ValueError, Author.objects.annotate, book_contact_set=Avg('friends__age')) + def test_pickle(self): # Regression for #10197 -- Queries with aggregates can be pickled. # First check that pickling is possible at all. No crash = success