fields.py 12 KB

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