Skip to content

Instantly share code, notes, and snippets.

@miki725
Last active March 27, 2017 06:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miki725/ce26d8b6ee2f3075884a to your computer and use it in GitHub Desktop.
Save miki725/ce26d8b6ee2f3075884a to your computer and use it in GitHub Desktop.
--- 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