Aggregation class "Sum" with Case

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from django.db import models

class SQLSumCase(models.sql.aggregates.Aggregate):
    is_ordinal = True
    sql_function = 'SUM'
    sql_template = "%(function)s(CASE %(case)s 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): # TODO
    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

More like this

  1. Aggregation class "Count" with Case by marinho 2 years, 10 months ago
  2. Widget for Money values on Geraldo Reports by marinho 4 years, 1 month ago
  3. SectionedForm by marinho 4 years, 11 months ago
  4. Generating aggregate data across generic relations by coleifer 3 years ago
  5. Widget for DateTime values on Geraldo Reports by marinho 4 years, 1 month ago

Comments

marinho (on July 9, 2010):

Fixed bug with NULL cases

#

stan (on October 11, 2011):

Useful.

But it does not works when you have join (Ambiguous column etc).

The following patch works only when the case in SumCase is about a column from the main table. I will try to fix the mymodel__myattr case later.

class SQLSumCase(models.sql.aggregates.Aggregate): is_ordinal = True sql_function = 'SUM' sql_template = "%(function)s(CASE %(case)s 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)
    # FIXME: handle relations via double underscores. 
    else:
        extra['case'] = '"%s"."%s"'%(extra['source'].model._meta.db_table, extra['case'])

    if extra['when'] is None:
        extra['when'] = True
        extra['case'] += ' IS NULL '

    super(SQLSumCase, self).__init__(col, **extra)

#

(Forgotten your password?)