proxy.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. """
  2. The GeometryProxy object, allows for lazy-geometries. The proxy uses
  3. Python descriptors for instantiating and setting Geometry objects
  4. corresponding to geographic model fields.
  5. Thanks to Robert Coup for providing this functionality (see #4322).
  6. """
  7. from django.contrib.gis import memoryview
  8. from django.utils import six
  9. class GeometryProxy(object):
  10. def __init__(self, klass, field):
  11. """
  12. Proxy initializes on the given Geometry class (not an instance) and
  13. the GeometryField.
  14. """
  15. self._field = field
  16. self._klass = klass
  17. def __get__(self, obj, type=None):
  18. """
  19. This accessor retrieves the geometry, initializing it using the geometry
  20. class specified during initialization and the HEXEWKB value of the field.
  21. Currently, only GEOS or OGR geometries are supported.
  22. """
  23. if obj is None:
  24. # Accessed on a class, not an instance
  25. return self
  26. # Getting the value of the field.
  27. geom_value = obj.__dict__[self._field.attname]
  28. if isinstance(geom_value, self._klass):
  29. geom = geom_value
  30. elif (geom_value is None) or (geom_value == ''):
  31. geom = None
  32. else:
  33. # Otherwise, a Geometry object is built using the field's contents,
  34. # and the model's corresponding attribute is set.
  35. geom = self._klass(geom_value)
  36. setattr(obj, self._field.attname, geom)
  37. return geom
  38. def __set__(self, obj, value):
  39. """
  40. This accessor sets the proxied geometry with the geometry class
  41. specified during initialization. Values of None, HEXEWKB, or WKT may
  42. be used to set the geometry as well.
  43. """
  44. # The OGC Geometry type of the field.
  45. gtype = self._field.geom_type
  46. # The geometry type must match that of the field -- unless the
  47. # general GeometryField is used.
  48. if isinstance(value, self._klass) and (str(value.geom_type).upper() == gtype or gtype == 'GEOMETRY'):
  49. # Assigning the SRID to the geometry.
  50. if value.srid is None:
  51. value.srid = self._field.srid
  52. elif value is None or isinstance(value, six.string_types + (memoryview,)):
  53. # Set with None, WKT, HEX, or WKB
  54. pass
  55. else:
  56. raise TypeError('Cannot set %s GeometryProxy (%s) with value of type: %s' % (
  57. obj.__class__.__name__, gtype, type(value)))
  58. # Setting the objects dictionary with the value, and returning.
  59. obj.__dict__[self._field.attname] = value
  60. return value