Skip to content

Instantly share code, notes, and snippets.

@iambibhas
Last active August 29, 2015 14:02
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 iambibhas/4bac154baddbcbd795c6 to your computer and use it in GitHub Desktop.
Save iambibhas/4bac154baddbcbd795c6 to your computer and use it in GitHub Desktop.
Django PostgreSQL CASE WHEN aggregation
from django.db import models
class SQLSumCase(models.sql.aggregates.Aggregate):
is_ordinal = True
sql_function = 'SUM'
sql_template = "%(function)s(CASE WHEN %(when)s THEN %(field)s ELSE 0 END)"
def __init__(self, col, **extra):
if isinstance(extra['when'], basestring):
extra['when'] = "%s" % extra['when']
if not extra.get('case', None):
extra['case'] = '"%s"."%s"' % (extra['source'].model._meta.db_table, extra['source'].name)
if extra['when'] is None:
extra['when'] = True
extra['case'] += ' IS NULL '
super(SQLSumCase, self).__init__(col, **extra)
class SumCase(models.Aggregate):
name = 'SUM'
def add_to_query(self, query, alias, col, source, is_summary):
aggregate = SQLSumCase(col, source=source, is_summary=is_summary, **self.extra)
query.aggregates[alias] = aggregate
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment