fields.py 12 KB

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