This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- import datetime | |
+++ (clipboard) | |
@@ -113,7 +113,22 @@ | |
for val in six.itervalues(self.query.extra_select): | |
params.extend(val[1]) | |
- result = ['SELECT'] | |
+ result = [] | |
+ | |
+ is_subquery = False | |
+ distinct_fields = [] | |
+ if self.query.distinct and ordering: | |
+ distinct_ordering_pairs = zip(distinct_fields, ordering) | |
+ if not all(map(lambda i: i[0] == i[1], distinct_ordering_pairs)): | |
+ is_subquery = True | |
+ result += [ | |
+ 'SELECT', | |
+ '*', | |
+ 'FROM', | |
+ '(', | |
+ ] | |
+ | |
+ result.append('SELECT') | |
if self.query.distinct: | |
result.append(self.connection.ops.distinct_sql(distinct_fields)) | |
@@ -144,7 +159,7 @@ | |
result.append('HAVING %s' % having) | |
params.extend(h_params) | |
- if ordering: | |
+ if ordering and not is_subquery: | |
result.append('ORDER BY %s' % ', '.join(ordering)) | |
params.extend(o_params) | |
@@ -171,6 +186,11 @@ | |
# Finally do cleanup - get rid of the joins we created above. | |
self.query.reset_refcounts(self.refcounts_before) | |
+ | |
+ if is_subquery: | |
+ result.append(') result') | |
+ result.append('ORDER BY %s' % ', '.join(ordering)) | |
+ params.extend(o_params) | |
return ' '.join(result), tuple(params) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment