Skip to content

Instantly share code, notes, and snippets.

@mekicha
Last active November 24, 2021 19:38
Show Gist options
  • Save mekicha/b3d5e61683d5a6af642e4549eed95994 to your computer and use it in GitHub Desktop.
Save mekicha/b3d5e61683d5a6af642e4549eed95994 to your computer and use it in GitHub Desktop.
PostgreSQL specific Django Percentile aggregation function

Inspired by this gist

The class extends to calculate any percentile (not just median).

Example usage:

Percentile('some_field', percentile=0.5) # calculates median for the field
Percentile('some_field', percentile=0.9) # calculates the 90th percentile

For completeness, I can calculate the median age of some Student model like so:

Student.objects.aggregate(median_age=Percentile('age', percentile=0.5))

It also works when used in annotate query.

More info at the official django documentation site

from django.db.modesl import Aggregate, FloatField
class Percentile(Aggregate):
function = "PERCENTILE_CONT"
name = "median"
output_field = FloatField()
template = "%(function)s (%(percentile)s) WITHIN GROUP (ORDER BY %(expressions)s)"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment