Skip to content

Instantly share code, notes, and snippets.

@miki725 miki725/as_sql.diff
Last active Mar 27, 2017

Embed
What would you like to do?
--- 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
You can’t perform that action at this time.