db-api.txt 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. ======================
  2. GeoDjango Database API
  3. ======================
  4. .. _spatial-backends:
  5. Spatial Backends
  6. ================
  7. .. module:: django.contrib.gis.db.backends
  8. :synopsis: GeoDjango's spatial database backends.
  9. GeoDjango currently provides the following spatial database backends:
  10. * ``django.contrib.gis.db.backends.postgis``
  11. * ``django.contrib.gis.db.backends.mysql``
  12. * ``django.contrib.gis.db.backends.oracle``
  13. * ``django.contrib.gis.db.backends.spatialite``
  14. .. module:: django.contrib.gis.db.models
  15. :synopsis: GeoDjango's database API.
  16. .. _mysql-spatial-limitations:
  17. MySQL Spatial Limitations
  18. -------------------------
  19. MySQL's spatial extensions only support bounding box operations
  20. (what MySQL calls minimum bounding rectangles, or MBR). Specifically,
  21. `MySQL does not conform to the OGC standard
  22. <https://dev.mysql.com/doc/refman/en/spatial-relation-functions.html>`_:
  23. Currently, MySQL does not implement these functions
  24. [``Contains``, ``Crosses``, ``Disjoint``, ``Intersects``, ``Overlaps``,
  25. ``Touches``, ``Within``]
  26. according to the specification. Those that are implemented return
  27. the same result as the corresponding MBR-based functions.
  28. In other words, while spatial lookups such as :lookup:`contains <gis-contains>`
  29. are available in GeoDjango when using MySQL, the results returned are really
  30. equivalent to what would be returned when using :lookup:`bbcontains`
  31. on a different spatial backend.
  32. .. warning::
  33. True spatial indexes (R-trees) are only supported with
  34. MyISAM tables on MySQL. [#fnmysqlidx]_ In other words, when using
  35. MySQL spatial extensions you have to choose between fast spatial
  36. lookups and the integrity of your data -- MyISAM tables do
  37. not support transactions or foreign key constraints.
  38. Raster Support
  39. --------------
  40. ``RasterField`` is currently only implemented for the PostGIS backend. Spatial
  41. lookups are available for raster fields, but spatial database functions and
  42. aggregates aren't implemented for raster fields.
  43. .. versionchanged:: 1.10
  44. ``RasterField`` now supports spatial lookups.
  45. Creating and Saving Models with Geometry Fields
  46. ===============================================
  47. Here is an example of how to create a geometry object (assuming the ``Zipcode``
  48. model)::
  49. >>> from zipcode.models import Zipcode
  50. >>> z = Zipcode(code=77096, poly='POLYGON(( 10 10, 10 20, 20 20, 20 15, 10 10))')
  51. >>> z.save()
  52. :class:`~django.contrib.gis.geos.GEOSGeometry` objects may also be used to save geometric models::
  53. >>> from django.contrib.gis.geos import GEOSGeometry
  54. >>> poly = GEOSGeometry('POLYGON(( 10 10, 10 20, 20 20, 20 15, 10 10))')
  55. >>> z = Zipcode(code=77096, poly=poly)
  56. >>> z.save()
  57. Moreover, if the ``GEOSGeometry`` is in a different coordinate system (has a
  58. different SRID value) than that of the field, then it will be implicitly
  59. transformed into the SRID of the model's field, using the spatial database's
  60. transform procedure::
  61. >>> poly_3084 = GEOSGeometry('POLYGON(( 10 10, 10 20, 20 20, 20 15, 10 10))', srid=3084) # SRID 3084 is 'NAD83(HARN) / Texas Centric Lambert Conformal'
  62. >>> z = Zipcode(code=78212, poly=poly_3084)
  63. >>> z.save()
  64. >>> from django.db import connection
  65. >>> print(connection.queries[-1]['sql']) # printing the last SQL statement executed (requires DEBUG=True)
  66. INSERT INTO "geoapp_zipcode" ("code", "poly") VALUES (78212, ST_Transform(ST_GeomFromWKB('\\001 ... ', 3084), 4326))
  67. Thus, geometry parameters may be passed in using the ``GEOSGeometry`` object, WKT
  68. (Well Known Text [#fnwkt]_), HEXEWKB (PostGIS specific -- a WKB geometry in
  69. hexadecimal [#fnewkb]_), and GeoJSON [#fngeojson]_. Essentially, if the input is
  70. not a ``GEOSGeometry`` object, the geometry field will attempt to create a
  71. ``GEOSGeometry`` instance from the input.
  72. For more information creating :class:`~django.contrib.gis.geos.GEOSGeometry`
  73. objects, refer to the :ref:`GEOS tutorial <geos-tutorial>`.
  74. .. _creating-and-saving-raster-models:
  75. Creating and Saving Models with Raster Fields
  76. =============================================
  77. When creating raster models, the raster field will implicitly convert the input
  78. into a :class:`~django.contrib.gis.gdal.GDALRaster` using lazy-evaluation.
  79. The raster field will therefore accept any input that is accepted by the
  80. :class:`~django.contrib.gis.gdal.GDALRaster` constructor.
  81. Here is an example of how to create a raster object from a raster file
  82. ``volcano.tif`` (assuming the ``Elevation`` model)::
  83. >>> from elevation.models import Elevation
  84. >>> dem = Elevation(name='Volcano', rast='/path/to/raster/volcano.tif')
  85. >>> dem.save()
  86. :class:`~django.contrib.gis.gdal.GDALRaster` objects may also be used to save
  87. raster models::
  88. >>> from django.contrib.gis.gdal import GDALRaster
  89. >>> rast = GDALRaster({'width': 10, 'height': 10, 'name': 'Canyon', 'srid': 4326,
  90. ... 'scale': [0.1, -0.1], 'bands': [{"data": range(100)}]})
  91. >>> dem = Elevation(name='Canyon', rast=rast)
  92. >>> dem.save()
  93. Note that this equivalent to::
  94. >>> dem = Elevation.objects.create(
  95. ... name='Canyon',
  96. ... rast={'width': 10, 'height': 10, 'name': 'Canyon', 'srid': 4326,
  97. ... 'scale': [0.1, -0.1], 'bands': [{"data": range(100)}]},
  98. ... )
  99. .. _spatial-lookups-intro:
  100. Spatial Lookups
  101. ===============
  102. GeoDjango's lookup types may be used with any manager method like
  103. ``filter()``, ``exclude()``, etc. However, the lookup types unique to
  104. GeoDjango are only available on spatial fields.
  105. Filters on 'normal' fields (e.g. :class:`~django.db.models.CharField`)
  106. may be chained with those on geographic fields. Geographic lookups accept
  107. geometry and raster input on both sides and input types can be mixed freely.
  108. The general structure of geographic lookups is described below. A complete
  109. reference can be found in the :ref:`spatial lookup reference<spatial-lookups>`.
  110. Geometry Lookups
  111. ----------------
  112. Geographic queries with geometries take the following general form (assuming
  113. the ``Zipcode`` model used in the :doc:`model-api`)::
  114. >>> qs = Zipcode.objects.filter(<field>__<lookup_type>=<parameter>)
  115. >>> qs = Zipcode.objects.exclude(...)
  116. For example::
  117. >>> qs = Zipcode.objects.filter(poly__contains=pnt)
  118. >>> qs = Elevation.objects.filter(poly__contains=rst)
  119. In this case, ``poly`` is the geographic field, :lookup:`contains <gis-contains>`
  120. is the spatial lookup type, ``pnt`` is the parameter (which may be a
  121. :class:`~django.contrib.gis.geos.GEOSGeometry` object or a string of
  122. GeoJSON , WKT, or HEXEWKB), and ``rst`` is a
  123. :class:`~django.contrib.gis.gdal.GDALRaster` object.
  124. .. _spatial-lookup-raster:
  125. Raster Lookups
  126. --------------
  127. .. versionadded:: 1.10
  128. The raster lookup syntax is similar to the syntax for geometries. The only
  129. difference is that a band index can be specified as additional input. If no band
  130. index is specified, the first band is used by default (index ``0``). In that
  131. case the syntax is identical to the syntax for geometry lookups.
  132. To specify the band index, an additional parameter can be specified on both
  133. sides of the lookup. On the left hand side, the double underscore syntax is
  134. used to pass a band index. On the right hand side, a tuple of the raster and
  135. band index can be specified.
  136. This results in the following general form for lookups involving rasters
  137. (assuming the ``Elevation`` model used in the :doc:`model-api`)::
  138. >>> qs = Elevation.objects.filter(<field>__<lookup_type>=<parameter>)
  139. >>> qs = Elevation.objects.filter(<field>__<band_index>__<lookup_type>=<parameter>)
  140. >>> qs = Elevation.objects.filter(<field>__<lookup_type>=(<raster_input, <band_index>)
  141. For example::
  142. >>> qs = Elevation.objects.filter(rast__contains=geom)
  143. >>> qs = Elevation.objects.filter(rast__contains=rst)
  144. >>> qs = Elevation.objects.filter(rast__1__contains=geom)
  145. >>> qs = Elevation.objects.filter(rast__contains=(rst, 1))
  146. >>> qs = Elevation.objects.filter(rast__1__contains=(rst, 1))
  147. On the left hand side of the example, ``rast`` is the geographic raster field
  148. and :lookup:`contains <gis-contains>` is the spatial lookup type. On the right
  149. hand side, ``geom`` is a geometry input and ``rst`` is a
  150. :class:`~django.contrib.gis.gdal.GDALRaster` object. The band index defaults to
  151. ``0`` in the first two queries and is set to ``1`` on the others.
  152. While all spatial lookups can be used with raster objects on both sides, not all
  153. underlying operators natively accept raster input. For cases where the operator
  154. expects geometry input, the raster is automatically converted to a geometry.
  155. It's important to keep this in mind when interpreting the lookup results.
  156. The type of raster support is listed for all lookups in the :ref:`compatibility
  157. table <spatial-lookup-compatibility>`. Lookups involving rasters are currently
  158. only available for the PostGIS backend.
  159. .. _distance-queries:
  160. Distance Queries
  161. ================
  162. Introduction
  163. ------------
  164. Distance calculations with spatial data is tricky because, unfortunately,
  165. the Earth is not flat. Some distance queries with fields in a geographic
  166. coordinate system may have to be expressed differently because of
  167. limitations in PostGIS. Please see the :ref:`selecting-an-srid` section
  168. in the :doc:`model-api` documentation for more details.
  169. .. _distance-lookups-intro:
  170. Distance Lookups
  171. ----------------
  172. *Availability*: PostGIS, Oracle, SpatiaLite, PGRaster (Native)
  173. The following distance lookups are available:
  174. * :lookup:`distance_lt`
  175. * :lookup:`distance_lte`
  176. * :lookup:`distance_gt`
  177. * :lookup:`distance_gte`
  178. * :lookup:`dwithin`
  179. .. note::
  180. For *measuring*, rather than querying on distances, use the
  181. :class:`~django.contrib.gis.db.models.functions.Distance` function.
  182. Distance lookups take a tuple parameter comprising:
  183. #. A geometry or raster to base calculations from; and
  184. #. A number or :class:`~django.contrib.gis.measure.Distance` object containing the distance.
  185. If a :class:`~django.contrib.gis.measure.Distance` object is used,
  186. it may be expressed in any units (the SQL generated will use units
  187. converted to those of the field); otherwise, numeric parameters are assumed
  188. to be in the units of the field.
  189. .. note::
  190. In PostGIS, ``ST_Distance_Sphere`` does *not* limit the geometry types
  191. geographic distance queries are performed with. [#fndistsphere15]_ However,
  192. these queries may take a long time, as great-circle distances must be
  193. calculated on the fly for *every* row in the query. This is because the
  194. spatial index on traditional geometry fields cannot be used.
  195. For much better performance on WGS84 distance queries, consider using
  196. :ref:`geography columns <geography-type>` in your database instead because
  197. they are able to use their spatial index in distance queries.
  198. You can tell GeoDjango to use a geography column by setting ``geography=True``
  199. in your field definition.
  200. For example, let's say we have a ``SouthTexasCity`` model (from the
  201. `GeoDjango distance tests`__ ) on a *projected* coordinate system valid for cities
  202. in southern Texas::
  203. from django.contrib.gis.db import models
  204. class SouthTexasCity(models.Model):
  205. name = models.CharField(max_length=30)
  206. # A projected coordinate system (only valid for South Texas!)
  207. # is used, units are in meters.
  208. point = models.PointField(srid=32140)
  209. Then distance queries may be performed as follows::
  210. >>> from django.contrib.gis.geos import GEOSGeometry
  211. >>> from django.contrib.gis.measure import D # ``D`` is a shortcut for ``Distance``
  212. >>> from geoapp.models import SouthTexasCity
  213. # Distances will be calculated from this point, which does not have to be projected.
  214. >>> pnt = GEOSGeometry('POINT(-96.876369 29.905320)', srid=4326)
  215. # If numeric parameter, units of field (meters in this case) are assumed.
  216. >>> qs = SouthTexasCity.objects.filter(point__distance_lte=(pnt, 7000))
  217. # Find all Cities within 7 km, > 20 miles away, and > 100 chains away (an obscure unit)
  218. >>> qs = SouthTexasCity.objects.filter(point__distance_lte=(pnt, D(km=7)))
  219. >>> qs = SouthTexasCity.objects.filter(point__distance_gte=(pnt, D(mi=20)))
  220. >>> qs = SouthTexasCity.objects.filter(point__distance_gte=(pnt, D(chain=100)))
  221. Raster queries work the same way by simply replacing the geometry field
  222. ``point`` with a raster field, or the ``pnt`` object with a raster object, or
  223. both. To specify the band index of a raster input on the right hand side, a
  224. 3-tuple can be passed to the lookup as follows::
  225. >>> qs = SouthTexasCity.objects.filter(point__distance_gte=(rst, 2, D(km=7)))
  226. Where the band with index 2 (the third band) of the raster ``rst`` would be
  227. used for the lookup.
  228. __ https://github.com/django/django/blob/master/tests/gis_tests/distapp/models.py
  229. .. _compatibility-table:
  230. Compatibility Tables
  231. ====================
  232. .. _spatial-lookup-compatibility:
  233. Spatial Lookups
  234. ---------------
  235. The following table provides a summary of what spatial lookups are available
  236. for each spatial database backend. The PostGIS Raster (PGRaster) lookups are
  237. divided into the three categories described in the :ref:`raster lookup details
  238. <spatial-lookup-raster>`: native support ``N``, bilateral native support ``B``,
  239. and geometry conversion support ``C``.
  240. ================================= ========= ======== ============ ========== ========
  241. Lookup Type PostGIS Oracle MySQL [#]_ SpatiaLite PGRaster
  242. ================================= ========= ======== ============ ========== ========
  243. :lookup:`bbcontains` X X X N
  244. :lookup:`bboverlaps` X X X N
  245. :lookup:`contained` X X X N
  246. :lookup:`contains <gis-contains>` X X X X B
  247. :lookup:`contains_properly` X B
  248. :lookup:`coveredby` X X B
  249. :lookup:`covers` X X B
  250. :lookup:`crosses` X X C
  251. :lookup:`disjoint` X X X X B
  252. :lookup:`distance_gt` X X X N
  253. :lookup:`distance_gte` X X X N
  254. :lookup:`distance_lt` X X X N
  255. :lookup:`distance_lte` X X X N
  256. :lookup:`dwithin` X X X B
  257. :lookup:`equals` X X X X C
  258. :lookup:`exact` X X X X B
  259. :lookup:`intersects` X X X X B
  260. :lookup:`isvalid` X
  261. :lookup:`overlaps` X X X X B
  262. :lookup:`relate` X X X C
  263. :lookup:`same_as` X X X X B
  264. :lookup:`touches` X X X X B
  265. :lookup:`within` X X X X B
  266. :lookup:`left` X C
  267. :lookup:`right` X C
  268. :lookup:`overlaps_left` X B
  269. :lookup:`overlaps_right` X B
  270. :lookup:`overlaps_above` X C
  271. :lookup:`overlaps_below` X C
  272. :lookup:`strictly_above` X C
  273. :lookup:`strictly_below` X C
  274. ================================= ========= ======== ============ ========== ========
  275. .. _database-functions-compatibility:
  276. Database functions
  277. ------------------
  278. .. module:: django.contrib.gis.db.models.functions
  279. :synopsis: GeoDjango's database functions.
  280. The following table provides a summary of what geography-specific database
  281. functions are available on each spatial backend.
  282. ==================================== ======= ====== =========== ==========
  283. Function PostGIS Oracle MySQL SpatiaLite
  284. ==================================== ======= ====== =========== ==========
  285. :class:`Area` X X X X
  286. :class:`AsGeoJSON` X X
  287. :class:`AsGML` X X X
  288. :class:`AsKML` X X
  289. :class:`AsSVG` X X
  290. :class:`BoundingCircle` X
  291. :class:`Centroid` X X X X
  292. :class:`Difference` X X X (≥ 5.6.1) X
  293. :class:`Distance` X X X (≥ 5.6.1) X
  294. :class:`Envelope` X X X
  295. :class:`ForceRHR` X
  296. :class:`GeoHash` X X (LWGEOM)
  297. :class:`Intersection` X X X (≥ 5.6.1) X
  298. :class:`IsValid` X
  299. :class:`Length` X X X X
  300. :class:`MakeValid` X
  301. :class:`MemSize` X
  302. :class:`NumGeometries` X X X X
  303. :class:`NumPoints` X X X X
  304. :class:`Perimeter` X X X
  305. :class:`PointOnSurface` X X X
  306. :class:`Reverse` X X X
  307. :class:`Scale` X X
  308. :class:`SnapToGrid` X X
  309. :class:`SymDifference` X X X (≥ 5.6.1) X
  310. :class:`Transform` X X X
  311. :class:`Translate` X X
  312. :class:`Union` X X X (≥ 5.6.1) X
  313. ==================================== ======= ====== =========== ==========
  314. Aggregate Functions
  315. -------------------
  316. The following table provides a summary of what GIS-specific aggregate functions
  317. are available on each spatial backend. Please note that MySQL does not
  318. support any of these aggregates, and is thus excluded from the table.
  319. .. currentmodule:: django.contrib.gis.db.models
  320. ======================= ======= ====== ==========
  321. Aggregate PostGIS Oracle SpatiaLite
  322. ======================= ======= ====== ==========
  323. :class:`Collect` X X
  324. :class:`Extent` X X X
  325. :class:`Extent3D` X
  326. :class:`MakeLine` X X
  327. :class:`Union` X X X
  328. ======================= ======= ====== ==========
  329. .. rubric:: Footnotes
  330. .. [#fnwkt] *See* Open Geospatial Consortium, Inc., `OpenGIS Simple Feature Specification For SQL <http://www.opengis.org/docs/99-049.pdf>`_, Document 99-049 (May 5, 1999), at Ch. 3.2.5, p. 3-11 (SQL Textual Representation of Geometry).
  331. .. [#fnewkb] *See* `PostGIS EWKB, EWKT and Canonical Forms <http://postgis.net/docs/using_postgis_dbmanagement.html#EWKB_EWKT>`_, PostGIS documentation at Ch. 4.1.2.
  332. .. [#fngeojson] *See* Howard Butler, Martin Daly, Allan Doyle, Tim Schaub, & Christopher Schmidt, `The GeoJSON Format Specification <http://geojson.org/geojson-spec.html>`_, Revision 1.0 (June 16, 2008).
  333. .. [#fndistsphere15] *See* `PostGIS documentation <http://postgis.net/docs/ST_DistanceSphere.html>`_ on ``ST_DistanceSphere``.
  334. .. [#fnmysqlidx] *See* `Creating Spatial Indexes <https://dev.mysql.com/doc/refman/en/creating-spatial-indexes.html>`_
  335. in the MySQL Reference Manual:
  336. For MyISAM tables, ``SPATIAL INDEX`` creates an R-tree index. For storage
  337. engines that support nonspatial indexing of spatial columns, the engine
  338. creates a B-tree index. A B-tree index on spatial values will be useful
  339. for exact-value lookups, but not for range scans.
  340. .. [#] Refer :ref:`mysql-spatial-limitations` section for more details.