PageRenderTime 46ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/django/contrib/gis/db/models/fields.py

https://code.google.com/p/mango-py/
Python | 294 lines | 218 code | 22 blank | 54 comment | 19 complexity | 46e71eb11a743e8a805d7666a93cef55 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. from django.db.models.fields import Field
  2. from django.db.models.sql.expressions import SQLEvaluator
  3. from django.utils.translation import ugettext_lazy as _
  4. from django.contrib.gis import forms
  5. from django.contrib.gis.db.models.proxy import GeometryProxy
  6. from django.contrib.gis.geometry.backend import Geometry, GeometryException
  7. # Local cache of the spatial_ref_sys table, which holds SRID data for each
  8. # spatial database alias. This cache exists so that the database isn't queried
  9. # for SRID info each time a distance query is constructed.
  10. _srid_cache = {}
  11. def get_srid_info(srid, connection):
  12. """
  13. Returns the units, unit name, and spheroid WKT associated with the
  14. given SRID from the `spatial_ref_sys` (or equivalent) spatial database
  15. table for the given database connection. These results are cached.
  16. """
  17. global _srid_cache
  18. try:
  19. # The SpatialRefSys model for the spatial backend.
  20. SpatialRefSys = connection.ops.spatial_ref_sys()
  21. except NotImplementedError:
  22. # No `spatial_ref_sys` table in spatial backend (e.g., MySQL).
  23. return None, None, None
  24. if not connection.alias in _srid_cache:
  25. # Initialize SRID dictionary for database if it doesn't exist.
  26. _srid_cache[connection.alias] = {}
  27. if not srid in _srid_cache[connection.alias]:
  28. # Use `SpatialRefSys` model to query for spatial reference info.
  29. sr = SpatialRefSys.objects.using(connection.alias).get(srid=srid)
  30. units, units_name = sr.units
  31. spheroid = SpatialRefSys.get_spheroid(sr.wkt)
  32. _srid_cache[connection.alias][srid] = (units, units_name, spheroid)
  33. return _srid_cache[connection.alias][srid]
  34. class GeometryField(Field):
  35. "The base GIS field -- maps to the OpenGIS Specification Geometry type."
  36. # The OpenGIS Geometry name.
  37. geom_type = 'GEOMETRY'
  38. # Geodetic units.
  39. geodetic_units = ('Decimal Degree', 'degree')
  40. description = _("The base GIS field -- maps to the OpenGIS Specification Geometry type.")
  41. def __init__(self, verbose_name=None, srid=4326, spatial_index=True, dim=2,
  42. geography=False, **kwargs):
  43. """
  44. The initialization function for geometry fields. Takes the following
  45. as keyword arguments:
  46. srid:
  47. The spatial reference system identifier, an OGC standard.
  48. Defaults to 4326 (WGS84).
  49. spatial_index:
  50. Indicates whether to create a spatial index. Defaults to True.
  51. Set this instead of 'db_index' for geographic fields since index
  52. creation is different for geometry columns.
  53. dim:
  54. The number of dimensions for this geometry. Defaults to 2.
  55. extent:
  56. Customize the extent, in a 4-tuple of WGS 84 coordinates, for the
  57. geometry field entry in the `USER_SDO_GEOM_METADATA` table. Defaults
  58. to (-180.0, -90.0, 180.0, 90.0).
  59. tolerance:
  60. Define the tolerance, in meters, to use for the geometry field
  61. entry in the `USER_SDO_GEOM_METADATA` table. Defaults to 0.05.
  62. """
  63. # Setting the index flag with the value of the `spatial_index` keyword.
  64. self.spatial_index = spatial_index
  65. # Setting the SRID and getting the units. Unit information must be
  66. # easily available in the field instance for distance queries.
  67. self.srid = srid
  68. # Setting the dimension of the geometry field.
  69. self.dim = dim
  70. # Setting the verbose_name keyword argument with the positional
  71. # first parameter, so this works like normal fields.
  72. kwargs['verbose_name'] = verbose_name
  73. # Is this a geography rather than a geometry column?
  74. self.geography = geography
  75. # Oracle-specific private attributes for creating the entrie in
  76. # `USER_SDO_GEOM_METADATA`
  77. self._extent = kwargs.pop('extent', (-180.0, -90.0, 180.0, 90.0))
  78. self._tolerance = kwargs.pop('tolerance', 0.05)
  79. super(GeometryField, self).__init__(**kwargs)
  80. # The following functions are used to get the units, their name, and
  81. # the spheroid corresponding to the SRID of the GeometryField.
  82. def _get_srid_info(self, connection):
  83. # Get attributes from `get_srid_info`.
  84. self._units, self._units_name, self._spheroid = get_srid_info(self.srid, connection)
  85. def spheroid(self, connection):
  86. if not hasattr(self, '_spheroid'):
  87. self._get_srid_info(connection)
  88. return self._spheroid
  89. def units(self, connection):
  90. if not hasattr(self, '_units'):
  91. self._get_srid_info(connection)
  92. return self._units
  93. def units_name(self, connection):
  94. if not hasattr(self, '_units_name'):
  95. self._get_srid_info(connection)
  96. return self._units_name
  97. ### Routines specific to GeometryField ###
  98. def geodetic(self, connection):
  99. """
  100. Returns true if this field's SRID corresponds with a coordinate
  101. system that uses non-projected units (e.g., latitude/longitude).
  102. """
  103. return self.units_name(connection) in self.geodetic_units
  104. def get_distance(self, value, lookup_type, connection):
  105. """
  106. Returns a distance number in units of the field. For example, if
  107. `D(km=1)` was passed in and the units of the field were in meters,
  108. then 1000 would be returned.
  109. """
  110. return connection.ops.get_distance(self, value, lookup_type)
  111. def get_prep_value(self, value):
  112. """
  113. Spatial lookup values are either a parameter that is (or may be
  114. converted to) a geometry, or a sequence of lookup values that
  115. begins with a geometry. This routine will setup the geometry
  116. value properly, and preserve any other lookup parameters before
  117. returning to the caller.
  118. """
  119. if isinstance(value, SQLEvaluator):
  120. return value
  121. elif isinstance(value, (tuple, list)):
  122. geom = value[0]
  123. seq_value = True
  124. else:
  125. geom = value
  126. seq_value = False
  127. # When the input is not a GEOS geometry, attempt to construct one
  128. # from the given string input.
  129. if isinstance(geom, Geometry):
  130. pass
  131. elif isinstance(geom, basestring) or hasattr(geom, '__geo_interface__'):
  132. try:
  133. geom = Geometry(geom)
  134. except GeometryException:
  135. raise ValueError('Could not create geometry from lookup value.')
  136. else:
  137. raise ValueError('Cannot use object with type %s for a geometry lookup parameter.' % type(geom).__name__)
  138. # Assigning the SRID value.
  139. geom.srid = self.get_srid(geom)
  140. if seq_value:
  141. lookup_val = [geom]
  142. lookup_val.extend(value[1:])
  143. return tuple(lookup_val)
  144. else:
  145. return geom
  146. def get_srid(self, geom):
  147. """
  148. Returns the default SRID for the given geometry, taking into account
  149. the SRID set for the field. For example, if the input geometry
  150. has no SRID, then that of the field will be returned.
  151. """
  152. gsrid = geom.srid # SRID of given geometry.
  153. if gsrid is None or self.srid == -1 or (gsrid == -1 and self.srid != -1):
  154. return self.srid
  155. else:
  156. return gsrid
  157. ### Routines overloaded from Field ###
  158. def contribute_to_class(self, cls, name):
  159. super(GeometryField, self).contribute_to_class(cls, name)
  160. # Setup for lazy-instantiated Geometry object.
  161. setattr(cls, self.attname, GeometryProxy(Geometry, self))
  162. def db_type(self, connection):
  163. return connection.ops.geo_db_type(self)
  164. def formfield(self, **kwargs):
  165. defaults = {'form_class' : forms.GeometryField,
  166. 'null' : self.null,
  167. 'geom_type' : self.geom_type,
  168. 'srid' : self.srid,
  169. }
  170. defaults.update(kwargs)
  171. return super(GeometryField, self).formfield(**defaults)
  172. def get_db_prep_lookup(self, lookup_type, value, connection, prepared=False):
  173. """
  174. Prepare for the database lookup, and return any spatial parameters
  175. necessary for the query. This includes wrapping any geometry
  176. parameters with a backend-specific adapter and formatting any distance
  177. parameters into the correct units for the coordinate system of the
  178. field.
  179. """
  180. if lookup_type in connection.ops.gis_terms:
  181. # special case for isnull lookup
  182. if lookup_type == 'isnull':
  183. return []
  184. # Populating the parameters list, and wrapping the Geometry
  185. # with the Adapter of the spatial backend.
  186. if isinstance(value, (tuple, list)):
  187. params = [connection.ops.Adapter(value[0])]
  188. if lookup_type in connection.ops.distance_functions:
  189. # Getting the distance parameter in the units of the field.
  190. params += self.get_distance(value[1:], lookup_type, connection)
  191. elif lookup_type in connection.ops.truncate_params:
  192. # Lookup is one where SQL parameters aren't needed from the
  193. # given lookup value.
  194. pass
  195. else:
  196. params += value[1:]
  197. elif isinstance(value, SQLEvaluator):
  198. params = []
  199. else:
  200. params = [connection.ops.Adapter(value)]
  201. return params
  202. else:
  203. raise ValueError('%s is not a valid spatial lookup for %s.' %
  204. (lookup_type, self.__class__.__name__))
  205. def get_prep_lookup(self, lookup_type, value):
  206. if lookup_type == 'isnull':
  207. return bool(value)
  208. else:
  209. return self.get_prep_value(value)
  210. def get_db_prep_save(self, value, connection):
  211. "Prepares the value for saving in the database."
  212. if value is None:
  213. return None
  214. else:
  215. return connection.ops.Adapter(self.get_prep_value(value))
  216. def get_placeholder(self, value, connection):
  217. """
  218. Returns the placeholder for the geometry column for the
  219. given value.
  220. """
  221. return connection.ops.get_geom_placeholder(self, value)
  222. # The OpenGIS Geometry Type Fields
  223. class PointField(GeometryField):
  224. geom_type = 'POINT'
  225. description = _("Point")
  226. class LineStringField(GeometryField):
  227. geom_type = 'LINESTRING'
  228. description = _("Line string")
  229. class PolygonField(GeometryField):
  230. geom_type = 'POLYGON'
  231. description = _("Polygon")
  232. class MultiPointField(GeometryField):
  233. geom_type = 'MULTIPOINT'
  234. description = _("Multi-point")
  235. class MultiLineStringField(GeometryField):
  236. geom_type = 'MULTILINESTRING'
  237. description = _("Multi-line string")
  238. class MultiPolygonField(GeometryField):
  239. geom_type = 'MULTIPOLYGON'
  240. description = _("Multi polygon")
  241. class GeometryCollectionField(GeometryField):
  242. geom_type = 'GEOMETRYCOLLECTION'
  243. description = _("Geometry collection")