Index: django/db/models/sql/query.py =================================================================== --- django/db/models/sql/query.py (revision 7922) +++ django/db/models/sql/query.py (working copy) @@ -252,7 +252,7 @@ # This must come after 'select' and 'ordering' -- see docstring of # get_from_clause() for details. - from_, f_params = self.get_from_clause() + from_, f_params = self.get_from_clause(with_limits) where, w_params = self.where.as_sql(qn=self.quote_name_unless_alias) params = list(self.extra_select_params) @@ -283,7 +283,7 @@ if ordering: result.append('ORDER BY %s' % ', '.join(ordering)) - if with_limits: + if self.outer_limits: if self.high_mark is not None: result.append('LIMIT %d' % (self.high_mark - self.low_mark)) if self.low_mark: @@ -502,7 +502,7 @@ return result, None return result, aliases - def get_from_clause(self): + def get_from_clause(self, with_limits): """ Returns a list of strings that are joined together to go after the "FROM" part of the query, as well as a list any extra parameters that @@ -517,6 +517,7 @@ qn = self.quote_name_unless_alias qn2 = self.connection.ops.quote_name first = True + self.outer_limits = True for alias in self.tables: if not self.alias_refcount[alias]: continue @@ -533,7 +534,25 @@ qn2(lhs_col), qn(alias), qn2(col))) else: connector = not first and ', ' or '' - result.append('%s%s%s' % (connector, qn(name), alias_str)) + where, w_params = self.where.as_sql(qn=self.quote_name_unless_alias) + if not where and first and with_limits and (self.high_mark or self.low_mark) and len(self.tables) > 1: + self.outer_limits = False + result.append('(SELECT * FROM %s' % qn(name)) + if self.high_mark is not None: + result.append('LIMIT %d' % (self.high_mark - self.low_mark)) + if self.low_mark: + if self.high_mark is None: + val = self.connection.ops.no_limit_value() + if val: + result.append('LIMIT %d' % val) + result.append('OFFSET %d' % self.low_mark) + my_alias = alias_str + if not my_alias: + my_alias = name + result.append(') %s' % qn(my_alias)) + #assert False, result + else: + result.append('%s%s%s' % (connector, qn(name), alias_str)) first = False for t in self.extra_tables: alias, unused = self.table_alias(t)