general.py 1.5 KB

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