aggregates.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. """
  2. Classes to represent the definitions of aggregate functions.
  3. """
  4. from django.db.models.constants import LOOKUP_SEP
  5. def refs_aggregate(lookup_parts, aggregates):
  6. """
  7. A little helper method to check if the lookup_parts contains references
  8. to the given aggregates set. Because the LOOKUP_SEP is contained in the
  9. default annotation names we must check each prefix of the lookup_parts
  10. for match.
  11. """
  12. for i in range(len(lookup_parts) + 1):
  13. if LOOKUP_SEP.join(lookup_parts[0:i]) in aggregates:
  14. return True
  15. return False
  16. class Aggregate(object):
  17. """
  18. Default Aggregate definition.
  19. """
  20. def __init__(self, lookup, **extra):
  21. """Instantiate a new aggregate.
  22. * lookup is the field on which the aggregate operates.
  23. * extra is a dictionary of additional data to provide for the
  24. aggregate definition
  25. Also utilizes the class variables:
  26. * name, the identifier for this aggregate function.
  27. """
  28. self.lookup = lookup
  29. self.extra = extra
  30. def _default_alias(self):
  31. return '%s__%s' % (self.lookup, self.name.lower())
  32. default_alias = property(_default_alias)
  33. def add_to_query(self, query, alias, col, source, is_summary):
  34. """Add the aggregate to the nominated query.
  35. This method is used to convert the generic Aggregate definition into a
  36. backend-specific definition.
  37. * query is the backend-specific query instance to which the aggregate
  38. is to be added.
  39. * col is a column reference describing the subject field
  40. of the aggregate. It can be an alias, or a tuple describing
  41. a table and column name.
  42. * source is the underlying field or aggregate definition for
  43. the column reference. If the aggregate is not an ordinal or
  44. computed type, this reference is used to determine the coerced
  45. output type of the aggregate.
  46. * is_summary is a boolean that is set True if the aggregate is a
  47. summary value rather than an annotation.
  48. """
  49. klass = getattr(query.aggregates_module, self.name)
  50. aggregate = klass(col, source=source, is_summary=is_summary, **self.extra)
  51. query.aggregates[alias] = aggregate
  52. class Avg(Aggregate):
  53. name = 'Avg'
  54. class Count(Aggregate):
  55. name = 'Count'
  56. class Max(Aggregate):
  57. name = 'Max'
  58. class Min(Aggregate):
  59. name = 'Min'
  60. class StdDev(Aggregate):
  61. name = 'StdDev'
  62. class Sum(Aggregate):
  63. name = 'Sum'
  64. class Variance(Aggregate):
  65. name = 'Variance'