Skip to content

Instantly share code, notes, and snippets.

@ketanbhatt
Created July 8, 2017 11:04
Show Gist options
  • Save ketanbhatt/609b9fb71e82bcd10b7c436c7dc3b09b to your computer and use it in GitHub Desktop.
Save ketanbhatt/609b9fb71e82bcd10b7c436c7dc3b09b to your computer and use it in GitHub Desktop.
Query with RawAnnotation
class RawAnnotation(RawSQL):
"""
RawSQL also aggregates the SQL to the `group by` clause which defeats the purpose of adding it to an Annotation.
"""
def get_group_by_cols(self):
return []
# The Query
q = MyModel.objects.values('some_fk_id').annotate(
avg_duration=Avg('duration'),
perc_90_duration=RawAnnotation('percentile_disc(%s) WITHIN GROUP (ORDER BY duration)', (0.9,)),
)
print q.query
# SELECT "some_fk_id",
# AVG("duration") AS "avg_duration",
# (percentile_disc(0.9) WITHIN
# GROUP (
# ORDER BY duration)) AS "perc_90_duration"
# FROM "mymodel"
# GROUP BY "some_fk_id"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment