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.

general.py 1.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. from django.contrib.postgres.fields import ArrayField, JSONField
  2. from django.db.models.aggregates import Aggregate
  3. from .mixins import OrderableAggMixin
  4. __all__ = [
  5. 'ArrayAgg', 'BitAnd', 'BitOr', 'BoolAnd', 'BoolOr', 'JSONBAgg', 'StringAgg',
  6. ]
  7. class ArrayAgg(OrderableAggMixin, Aggregate):
  8. function = 'ARRAY_AGG'
  9. template = '%(function)s(%(distinct)s%(expressions)s %(ordering)s)'
  10. allow_distinct = True
  11. @property
  12. def output_field(self):
  13. return ArrayField(self.source_expressions[0].output_field)
  14. def convert_value(self, value, expression, connection):
  15. if not value:
  16. return []
  17. return value
  18. class BitAnd(Aggregate):
  19. function = 'BIT_AND'
  20. class BitOr(Aggregate):
  21. function = 'BIT_OR'
  22. class BoolAnd(Aggregate):
  23. function = 'BOOL_AND'
  24. class BoolOr(Aggregate):
  25. function = 'BOOL_OR'
  26. class JSONBAgg(Aggregate):
  27. function = 'JSONB_AGG'
  28. output_field = JSONField()
  29. def convert_value(self, value, expression, connection):
  30. if not value:
  31. return []
  32. return value
  33. class StringAgg(OrderableAggMixin, Aggregate):
  34. function = 'STRING_AGG'
  35. template = "%(function)s(%(distinct)s%(expressions)s, '%(delimiter)s'%(ordering)s)"
  36. allow_distinct = True
  37. def __init__(self, expression, delimiter, **extra):
  38. super().__init__(expression, delimiter=delimiter, **extra)
  39. def convert_value(self, value, expression, connection):
  40. if not value:
  41. return ''
  42. return value