summaryrefslogtreecommitdiff
path: root/django/db/models/sql
diff options
context:
space:
mode:
Diffstat (limited to 'django/db/models/sql')
-rw-r--r--django/db/models/sql/datastructures.py4
-rw-r--r--django/db/models/sql/query.py16
2 files changed, 13 insertions, 7 deletions
diff --git a/django/db/models/sql/datastructures.py b/django/db/models/sql/datastructures.py
index af3db23e02..59343aa515 100644
--- a/django/db/models/sql/datastructures.py
+++ b/django/db/models/sql/datastructures.py
@@ -50,12 +50,14 @@ class Count(Aggregate):
quote_func = lambda x: x
if isinstance(self.col, (list, tuple)):
col = ('%s.%s' % tuple([quote_func(c) for c in self.col]))
+ elif hasattr(self.col, 'as_sql'):
+ col = self.col.as_sql(quote_func)
else:
col = self.col
if self.distinct:
return 'COUNT(DISTINCT %s)' % col
else:
- return 'COUNT(%s)' % self.col
+ return 'COUNT(%s)' % col
class Date(object):
"""
diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py
index d9a558e522..2a5ee616d8 100644
--- a/django/db/models/sql/query.py
+++ b/django/db/models/sql/query.py
@@ -193,6 +193,8 @@ class Query(object):
if obj.distinct and len(obj.select) > 1:
obj = self.clone(CountQuery, _query=obj, where=WhereNode(),
distinct=False)
+ obj.select = []
+ obj.extra_select = SortedDict()
obj.add_count_column()
data = obj.execute_sql(SINGLE)
if not data:
@@ -1008,13 +1010,18 @@ class Query(object):
def add_count_column(self):
"""
- Converts the query to do count(*) or count(distinct(pk)) in order to
+ Converts the query to do count(...) or count(distinct(pk)) in order to
get its size.
"""
# TODO: When group_by support is added, this needs to be adjusted so
# that it doesn't totally overwrite the select list.
if not self.distinct:
- select = Count()
+ if not self.select:
+ select = Count()
+ else:
+ assert len(self.select) == 1, \
+ "Cannot add count col with multiple cols in 'select': %r" % self.select
+ select = Count(self.select[0])
else:
opts = self.model._meta
if not self.select:
@@ -1229,11 +1236,8 @@ class DateQuery(Query):
select = Date((alias, column), lookup_type,
self.connection.ops.date_trunc_sql)
self.select = [select]
+ self.distinct = True
self.order_by = order == 'ASC' and [1] or [-1]
- if self.connection.features.allows_group_by_ordinal:
- self.group_by = [1]
- else:
- self.group_by = [select]
class CountQuery(Query):
"""