Development of an internal social media platform with personalised dashboards for students
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.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. from django.contrib.postgres.fields import ArrayField, JSONField
  2. from django.db.models.aggregates import Aggregate
  3. __all__ = [
  4. 'ArrayAgg', 'BitAnd', 'BitOr', 'BoolAnd', 'BoolOr', 'JSONBAgg', 'StringAgg',
  5. ]
  6. class ArrayAgg(Aggregate):
  7. function = 'ARRAY_AGG'
  8. template = '%(function)s(%(distinct)s%(expressions)s)'
  9. @property
  10. def output_field(self):
  11. return ArrayField(self.source_expressions[0].output_field)
  12. def __init__(self, expression, distinct=False, **extra):
  13. super().__init__(expression, distinct='DISTINCT ' if distinct else '', **extra)
  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(Aggregate):
  34. function = 'STRING_AGG'
  35. template = "%(function)s(%(distinct)s%(expressions)s, '%(delimiter)s')"
  36. def __init__(self, expression, delimiter, distinct=False, **extra):
  37. distinct = 'DISTINCT ' if distinct else ''
  38. super().__init__(expression, delimiter=delimiter, distinct=distinct, **extra)
  39. def convert_value(self, value, expression, connection):
  40. if not value:
  41. return ''
  42. return value