fields.py 14 KB

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