You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

aggregates.py 5.7KB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. """
  2. Classes to represent the definitions of aggregate functions.
  3. """
  4. from django.core.exceptions import FieldError
  5. from django.db.models.expressions import Case, Func, Star, When
  6. from django.db.models.fields import IntegerField
  7. from django.db.models.functions.mixins import (
  8. FixDurationInputMixin, NumericOutputFieldMixin,
  9. )
  10. __all__ = [
  11. 'Aggregate', 'Avg', 'Count', 'Max', 'Min', 'StdDev', 'Sum', 'Variance',
  12. ]
  13. class Aggregate(Func):
  14. template = '%(function)s(%(distinct)s%(expressions)s)'
  15. contains_aggregate = True
  16. name = None
  17. filter_template = '%s FILTER (WHERE %%(filter)s)'
  18. window_compatible = True
  19. allow_distinct = False
  20. def __init__(self, *expressions, distinct=False, filter=None, **extra):
  21. if distinct and not self.allow_distinct:
  22. raise TypeError("%s does not allow distinct." % self.__class__.__name__)
  23. self.distinct = distinct
  24. self.filter = filter
  25. super().__init__(*expressions, **extra)
  26. def get_source_fields(self):
  27. # Don't return the filter expression since it's not a source field.
  28. return [e._output_field_or_none for e in super().get_source_expressions()]
  29. def get_source_expressions(self):
  30. source_expressions = super().get_source_expressions()
  31. if self.filter:
  32. return source_expressions + [self.filter]
  33. return source_expressions
  34. def set_source_expressions(self, exprs):
  35. self.filter = self.filter and exprs.pop()
  36. return super().set_source_expressions(exprs)
  37. def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
  38. # Aggregates are not allowed in UPDATE queries, so ignore for_save
  39. c = super().resolve_expression(query, allow_joins, reuse, summarize)
  40. c.filter = c.filter and c.filter.resolve_expression(query, allow_joins, reuse, summarize)
  41. if not summarize:
  42. # Call Aggregate.get_source_expressions() to avoid
  43. # returning self.filter and including that in this loop.
  44. expressions = super(Aggregate, c).get_source_expressions()
  45. for index, expr in enumerate(expressions):
  46. if expr.contains_aggregate:
  47. before_resolved = self.get_source_expressions()[index]
  48. name = before_resolved.name if hasattr(before_resolved, 'name') else repr(before_resolved)
  49. raise FieldError("Cannot compute %s('%s'): '%s' is an aggregate" % (c.name, name, name))
  50. return c
  51. @property
  52. def default_alias(self):
  53. expressions = self.get_source_expressions()
  54. if len(expressions) == 1 and hasattr(expressions[0], 'name'):
  55. return '%s__%s' % (expressions[0].name, self.name.lower())
  56. raise TypeError("Complex expressions require an alias")
  57. def get_group_by_cols(self):
  58. return []
  59. def as_sql(self, compiler, connection, **extra_context):
  60. extra_context['distinct'] = 'DISTINCT ' if self.distinct else ''
  61. if self.filter:
  62. if connection.features.supports_aggregate_filter_clause:
  63. filter_sql, filter_params = self.filter.as_sql(compiler, connection)
  64. template = self.filter_template % extra_context.get('template', self.template)
  65. sql, params = super().as_sql(
  66. compiler, connection, template=template, filter=filter_sql,
  67. **extra_context
  68. )
  69. return sql, params + filter_params
  70. else:
  71. copy = self.copy()
  72. copy.filter = None
  73. source_expressions = copy.get_source_expressions()
  74. condition = When(self.filter, then=source_expressions[0])
  75. copy.set_source_expressions([Case(condition)] + source_expressions[1:])
  76. return super(Aggregate, copy).as_sql(compiler, connection, **extra_context)
  77. return super().as_sql(compiler, connection, **extra_context)
  78. def _get_repr_options(self):
  79. options = super()._get_repr_options()
  80. if self.distinct:
  81. options['distinct'] = self.distinct
  82. if self.filter:
  83. options['filter'] = self.filter
  84. return options
  85. class Avg(FixDurationInputMixin, NumericOutputFieldMixin, Aggregate):
  86. function = 'AVG'
  87. name = 'Avg'
  88. class Count(Aggregate):
  89. function = 'COUNT'
  90. name = 'Count'
  91. output_field = IntegerField()
  92. allow_distinct = True
  93. def __init__(self, expression, filter=None, **extra):
  94. if expression == '*':
  95. expression = Star()
  96. if isinstance(expression, Star) and filter is not None:
  97. raise ValueError('Star cannot be used with filter. Please specify a field.')
  98. super().__init__(expression, filter=filter, **extra)
  99. def convert_value(self, value, expression, connection):
  100. return 0 if value is None else value
  101. class Max(Aggregate):
  102. function = 'MAX'
  103. name = 'Max'
  104. class Min(Aggregate):
  105. function = 'MIN'
  106. name = 'Min'
  107. class StdDev(NumericOutputFieldMixin, Aggregate):
  108. name = 'StdDev'
  109. def __init__(self, expression, sample=False, **extra):
  110. self.function = 'STDDEV_SAMP' if sample else 'STDDEV_POP'
  111. super().__init__(expression, **extra)
  112. def _get_repr_options(self):
  113. return {**super()._get_repr_options(), 'sample': self.function == 'STDDEV_SAMP'}
  114. class Sum(FixDurationInputMixin, Aggregate):
  115. function = 'SUM'
  116. name = 'Sum'
  117. class Variance(NumericOutputFieldMixin, Aggregate):
  118. name = 'Variance'
  119. def __init__(self, expression, sample=False, **extra):
  120. self.function = 'VAR_SAMP' if sample else 'VAR_POP'
  121. super().__init__(expression, **extra)
  122. def _get_repr_options(self):
  123. return {**super()._get_repr_options(), 'sample': self.function == 'VAR_SAMP'}