Created
July 8, 2017 11:04
-
-
Save ketanbhatt/609b9fb71e82bcd10b7c436c7dc3b09b to your computer and use it in GitHub Desktop.
Query with RawAnnotation
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
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