Задать вопрос

Тел: +7 965 3737 888

470

Просмотров

3

Ответов

Aggregation class "Sum" with Case

<p>Just use it like below:</p>
from downloaded_file import SumCase
MyClass.objects.aggregate(
  sum1=SumCase('salary', case='salary &lt; 4', when=True),
  sum1=SumCase('salary', case='type', when='director'),
)

Вопрос полезен? Да0/Нет0
file_5106.py(946.0б)
None

Ответы (3):

Ответadickey:17.03.2014
Ответ полезен? Да0/Нет0

Nice custom aggregation example but I think for this custom aggregation to work properly 'is_ordinal' will have to be set to False. From the django source:

Ответstan:11.10.2011
Ответ полезен? Да0/Нет0

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)

Ответmarinho:09.07.2010
Ответ полезен? Да0/Нет0

Fixed bug with NULL cases