Aggregation class "Count" 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 SQLCountCase(models.sql.aggregates.Aggregate):
    is_ordinal = True
    sql_function = 'COUNT'
    sql_template = "%(function)s(CASE %(case)s WHEN %(when)s THEN 1 ELSE null 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(SQLCountCase, self).__init__(col, **extra)

class CountCase(models.Aggregate):
    name = 'COUNT'

    def add_to_query(self, query, alias, col, source, is_summary):
        aggregate = SQLCountCase(col, source=source, is_summary=is_summary, **self.extra)
        query.aggregates[alias] = aggregate

More like this

  1. Aggregation class "Sum" with Case by marinho 3 years, 9 months ago
  2. Generating aggregate data across generic relations by coleifer 3 years, 11 months ago
  3. Annotate queryset with comment count by fivethreeo 5 years, 6 months ago
  4. Auto rendering decorator with options by Batiste 6 years, 2 months ago
  5. Enhancing template tags with "as variable" syntax by ctrochalakis 4 years, 7 months ago

Comments

marinho (on July 9, 2010):

Fixed bug with NULL cases

#

(Forgotten your password?)