aggregates.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. from django.db.models.sql import aggregates
  2. from django.db.models.sql.aggregates import * # NOQA
  3. from django.contrib.gis.db.models.fields import GeometryField
  4. __all__ = ['Collect', 'Extent', 'Extent3D', 'MakeLine', 'Union'] + aggregates.__all__
  5. class GeoAggregate(Aggregate):
  6. # Default SQL template for spatial aggregates.
  7. sql_template = '%(function)s(%(field)s)'
  8. # Conversion class, if necessary.
  9. conversion_class = None
  10. # Flags for indicating the type of the aggregate.
  11. is_extent = False
  12. def __init__(self, col, source=None, is_summary=False, tolerance=0.05, **extra):
  13. super(GeoAggregate, self).__init__(col, source, is_summary, **extra)
  14. # Required by some Oracle aggregates.
  15. self.tolerance = tolerance
  16. # Can't use geographic aggregates on non-geometry fields.
  17. if not isinstance(self.source, GeometryField):
  18. raise ValueError('Geospatial aggregates only allowed on geometry fields.')
  19. def as_sql(self, qn, connection):
  20. "Return the aggregate, rendered as SQL with parameters."
  21. if connection.ops.oracle:
  22. self.extra['tolerance'] = self.tolerance
  23. params = []
  24. if hasattr(self.col, 'as_sql'):
  25. field_name, params = self.col.as_sql(qn, connection)
  26. elif isinstance(self.col, (list, tuple)):
  27. field_name = '.'.join(qn(c) for c in self.col)
  28. else:
  29. field_name = self.col
  30. sql_template, sql_function = connection.ops.spatial_aggregate_sql(self)
  31. substitutions = {
  32. 'function': sql_function,
  33. 'field': field_name
  34. }
  35. substitutions.update(self.extra)
  36. return sql_template % substitutions, params
  37. class Collect(GeoAggregate):
  38. pass
  39. class Extent(GeoAggregate):
  40. is_extent = '2D'
  41. class Extent3D(GeoAggregate):
  42. is_extent = '3D'
  43. class MakeLine(GeoAggregate):
  44. pass
  45. class Union(GeoAggregate):
  46. pass