db-api.txt 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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. <http://dev.mysql.com/doc/refman/5.6/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. queries (such as lookups and distance) are not yet available for raster fields.
  42. Creating and Saving Models with Geometry Fields
  43. ===============================================
  44. Here is an example of how to create a geometry object (assuming the ``Zipcode``
  45. model)::
  46. >>> from zipcode.models import Zipcode
  47. >>> z = Zipcode(code=77096, poly='POLYGON(( 10 10, 10 20, 20 20, 20 15, 10 10))')
  48. >>> z.save()
  49. :class:`~django.contrib.gis.geos.GEOSGeometry` objects may also be used to save geometric models::
  50. >>> from django.contrib.gis.geos import GEOSGeometry
  51. >>> poly = GEOSGeometry('POLYGON(( 10 10, 10 20, 20 20, 20 15, 10 10))')
  52. >>> z = Zipcode(code=77096, poly=poly)
  53. >>> z.save()
  54. Moreover, if the ``GEOSGeometry`` is in a different coordinate system (has a
  55. different SRID value) than that of the field, then it will be implicitly
  56. transformed into the SRID of the model's field, using the spatial database's
  57. transform procedure::
  58. >>> 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'
  59. >>> z = Zipcode(code=78212, poly=poly_3084)
  60. >>> z.save()
  61. >>> from django.db import connection
  62. >>> print(connection.queries[-1]['sql']) # printing the last SQL statement executed (requires DEBUG=True)
  63. INSERT INTO "geoapp_zipcode" ("code", "poly") VALUES (78212, ST_Transform(ST_GeomFromWKB('\\001 ... ', 3084), 4326))
  64. Thus, geometry parameters may be passed in using the ``GEOSGeometry`` object, WKT
  65. (Well Known Text [#fnwkt]_), HEXEWKB (PostGIS specific -- a WKB geometry in
  66. hexadecimal [#fnewkb]_), and GeoJSON [#fngeojson]_ (requires GDAL). Essentially,
  67. if the input is not a ``GEOSGeometry`` object, the geometry field will attempt to
  68. create a ``GEOSGeometry`` instance from the input.
  69. For more information creating :class:`~django.contrib.gis.geos.GEOSGeometry`
  70. objects, refer to the :ref:`GEOS tutorial <geos-tutorial>`.
  71. .. _creating-and-saving-raster-models:
  72. Creating and Saving Models with Raster Fields
  73. =============================================
  74. .. versionadded:: 1.9
  75. When creating raster models, the raster field will implicitly convert the input
  76. into a :class:`~django.contrib.gis.gdal.GDALRaster` using lazy-evaluation.
  77. The raster field will therefore accept any input that is accepted by the
  78. :class:`~django.contrib.gis.gdal.GDALRaster` constructor.
  79. Here is an example of how to create a raster object from a raster file
  80. ``volcano.tif`` (assuming the ``Elevation`` model)::
  81. >>> from elevation.models import Elevation
  82. >>> dem = Elevation(name='Volcano', rast='/path/to/raster/volcano.tif')
  83. >>> dem.save()
  84. :class:`~django.contrib.gis.gdal.GDALRaster` objects may also be used to save
  85. raster models::
  86. >>> from django.contrib.gis.gdal import GDALRaster
  87. >>> rast = GDALRaster({'width': 10, 'height': 10, 'name': 'Canyon', 'srid': 4326,
  88. ... 'scale': [0.1, -0.1]'bands': [{"data": range(100)}]}
  89. >>> dem = Elevation(name='Canyon', rast=rast)
  90. >>> dem.save()
  91. Note that this equivalent to::
  92. >>> dem = Elevation.objects.create(
  93. ... name='Canyon',
  94. ... rast={'width': 10, 'height': 10, 'name': 'Canyon', 'srid': 4326,
  95. ... 'scale': [0.1, -0.1]'bands': [{"data": range(100)}]}
  96. ... )
  97. .. _spatial-lookups-intro:
  98. Spatial Lookups
  99. ===============
  100. GeoDjango's lookup types may be used with any manager method like
  101. ``filter()``, ``exclude()``, etc. However, the lookup types unique to
  102. GeoDjango are only available on geometry fields.
  103. Filters on 'normal' fields (e.g. :class:`~django.db.models.CharField`)
  104. may be chained with those on geographic fields. Thus, geographic queries
  105. take the following general form (assuming the ``Zipcode`` model used in the
  106. :doc:`model-api`)::
  107. >>> qs = Zipcode.objects.filter(<field>__<lookup_type>=<parameter>)
  108. >>> qs = Zipcode.objects.exclude(...)
  109. For example::
  110. >>> qs = Zipcode.objects.filter(poly__contains=pnt)
  111. In this case, ``poly`` is the geographic field, :lookup:`contains <gis-contains>`
  112. is the spatial lookup type, and ``pnt`` is the parameter (which may be a
  113. :class:`~django.contrib.gis.geos.GEOSGeometry` object or a string of
  114. GeoJSON , WKT, or HEXEWKB).
  115. A complete reference can be found in the :ref:`spatial lookup reference
  116. <spatial-lookups>`.
  117. .. _distance-queries:
  118. Distance Queries
  119. ================
  120. Introduction
  121. ------------
  122. Distance calculations with spatial data is tricky because, unfortunately,
  123. the Earth is not flat. Some distance queries with fields in a geographic
  124. coordinate system may have to be expressed differently because of
  125. limitations in PostGIS. Please see the :ref:`selecting-an-srid` section
  126. in the :doc:`model-api` documentation for more details.
  127. .. _distance-lookups-intro:
  128. Distance Lookups
  129. ----------------
  130. *Availability*: PostGIS, Oracle, SpatiaLite
  131. The following distance lookups are available:
  132. * :lookup:`distance_lt`
  133. * :lookup:`distance_lte`
  134. * :lookup:`distance_gt`
  135. * :lookup:`distance_gte`
  136. * :lookup:`dwithin`
  137. .. note::
  138. For *measuring*, rather than querying on distances, use the
  139. :class:`~django.contrib.gis.db.models.functions.Distance` function.
  140. Distance lookups take a tuple parameter comprising:
  141. #. A geometry to base calculations from; and
  142. #. A number or :class:`~django.contrib.gis.measure.Distance` object containing the distance.
  143. If a :class:`~django.contrib.gis.measure.Distance` object is used,
  144. it may be expressed in any units (the SQL generated will use units
  145. converted to those of the field); otherwise, numeric parameters are assumed
  146. to be in the units of the field.
  147. .. note::
  148. In PostGIS, ``ST_Distance_Sphere`` does *not* limit the geometry types
  149. geographic distance queries are performed with. [#fndistsphere15]_ However,
  150. these queries may take a long time, as great-circle distances must be
  151. calculated on the fly for *every* row in the query. This is because the
  152. spatial index on traditional geometry fields cannot be used.
  153. For much better performance on WGS84 distance queries, consider using
  154. :ref:`geography columns <geography-type>` in your database instead because
  155. they are able to use their spatial index in distance queries.
  156. You can tell GeoDjango to use a geography column by setting ``geography=True``
  157. in your field definition.
  158. For example, let's say we have a ``SouthTexasCity`` model (from the
  159. `GeoDjango distance tests`__ ) on a *projected* coordinate system valid for cities
  160. in southern Texas::
  161. from django.contrib.gis.db import models
  162. class SouthTexasCity(models.Model):
  163. name = models.CharField(max_length=30)
  164. # A projected coordinate system (only valid for South Texas!)
  165. # is used, units are in meters.
  166. point = models.PointField(srid=32140)
  167. Then distance queries may be performed as follows::
  168. >>> from django.contrib.gis.geos import fromstr
  169. >>> from django.contrib.gis.measure import D # ``D`` is a shortcut for ``Distance``
  170. >>> from geoapp.models import SouthTexasCity
  171. # Distances will be calculated from this point, which does not have to be projected.
  172. >>> pnt = fromstr('POINT(-96.876369 29.905320)', srid=4326)
  173. # If numeric parameter, units of field (meters in this case) are assumed.
  174. >>> qs = SouthTexasCity.objects.filter(point__distance_lte=(pnt, 7000))
  175. # Find all Cities within 7 km, > 20 miles away, and > 100 chains away (an obscure unit)
  176. >>> qs = SouthTexasCity.objects.filter(point__distance_lte=(pnt, D(km=7)))
  177. >>> qs = SouthTexasCity.objects.filter(point__distance_gte=(pnt, D(mi=20)))
  178. >>> qs = SouthTexasCity.objects.filter(point__distance_gte=(pnt, D(chain=100)))
  179. __ https://github.com/django/django/blob/master/tests/gis_tests/distapp/models.py
  180. .. _compatibility-table:
  181. Compatibility Tables
  182. ====================
  183. .. _spatial-lookup-compatibility:
  184. Spatial Lookups
  185. ---------------
  186. The following table provides a summary of what spatial lookups are available
  187. for each spatial database backend.
  188. ================================= ========= ======== ============ ==========
  189. Lookup Type PostGIS Oracle MySQL [#]_ SpatiaLite
  190. ================================= ========= ======== ============ ==========
  191. :lookup:`bbcontains` X X X
  192. :lookup:`bboverlaps` X X X
  193. :lookup:`contained` X X X
  194. :lookup:`contains <gis-contains>` X X X X
  195. :lookup:`contains_properly` X
  196. :lookup:`coveredby` X X
  197. :lookup:`covers` X X
  198. :lookup:`crosses` X X
  199. :lookup:`disjoint` X X X X
  200. :lookup:`distance_gt` X X X
  201. :lookup:`distance_gte` X X X
  202. :lookup:`distance_lt` X X X
  203. :lookup:`distance_lte` X X X
  204. :lookup:`dwithin` X X
  205. :lookup:`equals` X X X X
  206. :lookup:`exact` X X X X
  207. :lookup:`intersects` X X X X
  208. :lookup:`overlaps` X X X X
  209. :lookup:`relate` X X X
  210. :lookup:`same_as` X X X X
  211. :lookup:`touches` X X X X
  212. :lookup:`within` X X X X
  213. :lookup:`left` X
  214. :lookup:`right` X
  215. :lookup:`overlaps_left` X
  216. :lookup:`overlaps_right` X
  217. :lookup:`overlaps_above` X
  218. :lookup:`overlaps_below` X
  219. :lookup:`strictly_above` X
  220. :lookup:`strictly_below` X
  221. ================================= ========= ======== ============ ==========
  222. .. _database-functions-compatibility:
  223. Database functions
  224. ------------------
  225. .. module:: django.contrib.gis.db.models.functions
  226. :synopsis: GeoDjango's database functions.
  227. The following table provides a summary of what geography-specific database
  228. functions are available on each spatial backend.
  229. ==================================== ======= ====== ===== ==========
  230. Method PostGIS Oracle MySQL SpatiaLite
  231. ==================================== ======= ====== ===== ==========
  232. :class:`Area` X X X X
  233. :class:`AsGeoJSON` X X
  234. :class:`AsGML` X X X
  235. :class:`AsKML` X X
  236. :class:`AsSVG` X X
  237. :class:`BoundingCircle` X
  238. :class:`Centroid` X X X
  239. :class:`Difference` X X X
  240. :class:`Distance` X X X X
  241. :class:`Envelope` X X
  242. :class:`ForceRHR` X
  243. :class:`GeoHash` X
  244. :class:`Intersection` X X X
  245. :class:`Length` X X X X
  246. :class:`MemSize` X
  247. :class:`NumGeometries` X X X
  248. :class:`NumPoints` X X X
  249. :class:`Perimeter` X X X
  250. :class:`PointOnSurface` X X X
  251. :class:`Reverse` X X X (≥ 4.0)
  252. :class:`Scale` X X
  253. :class:`SnapToGrid` X X
  254. :class:`SymDifference` X X X
  255. :class:`Transform` X X X
  256. :class:`Translate` X X
  257. :class:`Union` X X X
  258. ==================================== ======= ====== ===== ==========
  259. Aggregate Functions
  260. -------------------
  261. The following table provides a summary of what GIS-specific aggregate functions
  262. are available on each spatial backend. Please note that MySQL does not
  263. support any of these aggregates, and is thus excluded from the table.
  264. .. currentmodule:: django.contrib.gis.db.models
  265. ======================= ======= ====== ==========
  266. Aggregate PostGIS Oracle SpatiaLite
  267. ======================= ======= ====== ==========
  268. :class:`Collect` X (from v3.0)
  269. :class:`Extent` X X (from v3.0)
  270. :class:`Extent3D` X
  271. :class:`MakeLine` X
  272. :class:`Union` X X X
  273. ======================= ======= ====== ==========
  274. .. rubric:: Footnotes
  275. .. [#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).
  276. .. [#fnewkb] *See* `PostGIS EWKB, EWKT and Canonical Forms <http://postgis.net/docs/manual-2.1/using_postgis_dbmanagement.html#EWKB_EWKT>`_, PostGIS documentation at Ch. 4.1.2.
  277. .. [#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).
  278. .. [#fndistsphere15] *See* `PostGIS documentation <http://postgis.net/docs/manual-2.1/ST_Distance_Sphere.html>`_ on ``ST_distance_sphere``.
  279. .. [#fnmysqlidx] *See* `Creating Spatial Indexes <http://dev.mysql.com/doc/refman/5.6/en/creating-spatial-indexes.html>`_
  280. in the MySQL Reference Manual:
  281. For MyISAM tables, ``SPATIAL INDEX`` creates an R-tree index. For storage
  282. engines that support nonspatial indexing of spatial columns, the engine
  283. creates a B-tree index. A B-tree index on spatial values will be useful
  284. for exact-value lookups, but not for range scans.
  285. .. [#] Refer :ref:`mysql-spatial-limitations` section for more details.