Last active
August 29, 2015 14:02
-
-
Save iambibhas/4bac154baddbcbd795c6 to your computer and use it in GitHub Desktop.
Django PostgreSQL CASE WHEN aggregation
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
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