From daf2bd3efe53cbfc1c9fd00222b8315708023792 Mon Sep 17 00:00:00 2001 From: Simon Charette Date: Sat, 29 Apr 2017 14:53:43 -0400 Subject: Fixed #28107 -- Disabled grouping of selected primary keys for unmanaged models. The grouping caused an issue with database views as PostgreSQL's query planer isn't smart enough to introspect primary keys through views. Django doesn't support database views but documents that unmanaged models should be used to query them. Thanks powderflask for the detailed report and investigation. --- django/db/models/sql/compiler.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) (limited to 'django/db/models/sql') diff --git a/django/db/models/sql/compiler.py b/django/db/models/sql/compiler.py index 14a727e998..2543755952 100644 --- a/django/db/models/sql/compiler.py +++ b/django/db/models/sql/compiler.py @@ -161,7 +161,12 @@ class SQLCompiler: # present in the grouped columns. This is done by identifying all # tables that have their primary key included in the grouped # columns and removing non-primary key columns referring to them. - pks = {expr for expr in expressions if hasattr(expr, 'target') and expr.target.primary_key} + # Unmanaged models are excluded because they could be representing + # database views on which the optimization might not be allowed. + pks = { + expr for expr in expressions + if hasattr(expr, 'target') and expr.target.primary_key and expr.target.model._meta.managed + } aliases = {expr.alias for expr in pks} expressions = [ expr for expr in expressions if expr in pks or getattr(expr, 'alias', None) not in aliases -- cgit v1.3