db-api.txt 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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. Creating and Saving Geographic Models
  39. =====================================
  40. Here is an example of how to create a geometry object (assuming the ``Zipcode``
  41. model)::
  42. >>> from zipcode.models import Zipcode
  43. >>> z = Zipcode(code=77096, poly='POLYGON(( 10 10, 10 20, 20 20, 20 15, 10 10))')
  44. >>> z.save()
  45. :class:`~django.contrib.gis.geos.GEOSGeometry` objects may also be used to save geometric models::
  46. >>> from django.contrib.gis.geos import GEOSGeometry
  47. >>> poly = GEOSGeometry('POLYGON(( 10 10, 10 20, 20 20, 20 15, 10 10))')
  48. >>> z = Zipcode(code=77096, poly=poly)
  49. >>> z.save()
  50. Moreover, if the ``GEOSGeometry`` is in a different coordinate system (has a
  51. different SRID value) than that of the field, then it will be implicitly
  52. transformed into the SRID of the model's field, using the spatial database's
  53. transform procedure::
  54. >>> 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'
  55. >>> z = Zipcode(code=78212, poly=poly_3084)
  56. >>> z.save()
  57. >>> from django.db import connection
  58. >>> print(connection.queries[-1]['sql']) # printing the last SQL statement executed (requires DEBUG=True)
  59. INSERT INTO "geoapp_zipcode" ("code", "poly") VALUES (78212, ST_Transform(ST_GeomFromWKB('\\001 ... ', 3084), 4326))
  60. Thus, geometry parameters may be passed in using the ``GEOSGeometry`` object, WKT
  61. (Well Known Text [#fnwkt]_), HEXEWKB (PostGIS specific -- a WKB geometry in
  62. hexadecimal [#fnewkb]_), and GeoJSON [#fngeojson]_ (requires GDAL). Essentially,
  63. if the input is not a ``GEOSGeometry`` object, the geometry field will attempt to
  64. create a ``GEOSGeometry`` instance from the input.
  65. For more information creating :class:`~django.contrib.gis.geos.GEOSGeometry`
  66. objects, refer to the :ref:`GEOS tutorial <geos-tutorial>`.
  67. .. _spatial-lookups-intro:
  68. Spatial Lookups
  69. ===============
  70. GeoDjango's lookup types may be used with any manager method like
  71. ``filter()``, ``exclude()``, etc. However, the lookup types unique to
  72. GeoDjango are only available on geometry fields.
  73. Filters on 'normal' fields (e.g. :class:`~django.db.models.CharField`)
  74. may be chained with those on geographic fields. Thus, geographic queries
  75. take the following general form (assuming the ``Zipcode`` model used in the
  76. :doc:`model-api`)::
  77. >>> qs = Zipcode.objects.filter(<field>__<lookup_type>=<parameter>)
  78. >>> qs = Zipcode.objects.exclude(...)
  79. For example::
  80. >>> qs = Zipcode.objects.filter(poly__contains=pnt)
  81. In this case, ``poly`` is the geographic field, :lookup:`contains <gis-contains>`
  82. is the spatial lookup type, and ``pnt`` is the parameter (which may be a
  83. :class:`~django.contrib.gis.geos.GEOSGeometry` object or a string of
  84. GeoJSON , WKT, or HEXEWKB).
  85. A complete reference can be found in the :ref:`spatial lookup reference
  86. <spatial-lookups>`.
  87. .. note::
  88. GeoDjango constructs spatial SQL with the :class:`GeoQuerySet`, a
  89. subclass of :class:`~django.db.models.query.QuerySet`. The
  90. :class:`GeoManager` instance attached to your model is what
  91. enables use of :class:`GeoQuerySet`.
  92. .. _distance-queries:
  93. Distance Queries
  94. ================
  95. Introduction
  96. ------------
  97. Distance calculations with spatial data is tricky because, unfortunately,
  98. the Earth is not flat. Some distance queries with fields in a geographic
  99. coordinate system may have to be expressed differently because of
  100. limitations in PostGIS. Please see the :ref:`selecting-an-srid` section
  101. in the :doc:`model-api` documentation for more details.
  102. .. _distance-lookups-intro:
  103. Distance Lookups
  104. ----------------
  105. *Availability*: PostGIS, Oracle, SpatiaLite
  106. The following distance lookups are available:
  107. * :lookup:`distance_lt`
  108. * :lookup:`distance_lte`
  109. * :lookup:`distance_gt`
  110. * :lookup:`distance_gte`
  111. * :lookup:`dwithin`
  112. .. note::
  113. For *measuring*, rather than querying on distances, use the
  114. :meth:`GeoQuerySet.distance` method.
  115. Distance lookups take a tuple parameter comprising:
  116. #. A geometry to base calculations from; and
  117. #. A number or :class:`~django.contrib.gis.measure.Distance` object containing the distance.
  118. If a :class:`~django.contrib.gis.measure.Distance` object is used,
  119. it may be expressed in any units (the SQL generated will use units
  120. converted to those of the field); otherwise, numeric parameters are assumed
  121. to be in the units of the field.
  122. .. note::
  123. In PostGIS 1.5, ``ST_Distance_Sphere`` does *not* limit the geometry types
  124. geographic distance queries are performed with. [#fndistsphere15]_ However,
  125. these queries may take a long time, as great-circle distances must be
  126. calculated on the fly for *every* row in the query. This is because the
  127. spatial index on traditional geometry fields cannot be used.
  128. For much better performance on WGS84 distance queries, consider using
  129. :ref:`geography columns <geography-type>` in your database instead because
  130. they are able to use their spatial index in distance queries.
  131. You can tell GeoDjango to use a geography column by setting ``geography=True``
  132. in your field definition.
  133. For example, let's say we have a ``SouthTexasCity`` model (from the
  134. `GeoDjango distance tests`__ ) on a *projected* coordinate system valid for cities
  135. in southern Texas::
  136. from django.contrib.gis.db import models
  137. class SouthTexasCity(models.Model):
  138. name = models.CharField(max_length=30)
  139. # A projected coordinate system (only valid for South Texas!)
  140. # is used, units are in meters.
  141. point = models.PointField(srid=32140)
  142. objects = models.GeoManager()
  143. Then distance queries may be performed as follows::
  144. >>> from django.contrib.gis.geos import *
  145. >>> from django.contrib.gis.measure import D # ``D`` is a shortcut for ``Distance``
  146. >>> from geoapp import SouthTexasCity
  147. # Distances will be calculated from this point, which does not have to be projected.
  148. >>> pnt = fromstr('POINT(-96.876369 29.905320)', srid=4326)
  149. # If numeric parameter, units of field (meters in this case) are assumed.
  150. >>> qs = SouthTexasCity.objects.filter(point__distance_lte=(pnt, 7000))
  151. # Find all Cities within 7 km, > 20 miles away, and > 100 chains away (an obscure unit)
  152. >>> qs = SouthTexasCity.objects.filter(point__distance_lte=(pnt, D(km=7)))
  153. >>> qs = SouthTexasCity.objects.filter(point__distance_gte=(pnt, D(mi=20)))
  154. >>> qs = SouthTexasCity.objects.filter(point__distance_gte=(pnt, D(chain=100)))
  155. __ https://github.com/django/django/blob/master/django/contrib/gis/tests/distapp/models.py
  156. .. _compatibility-table:
  157. Compatibility Tables
  158. ====================
  159. .. _spatial-lookup-compatibility:
  160. Spatial Lookups
  161. ---------------
  162. The following table provides a summary of what spatial lookups are available
  163. for each spatial database backend.
  164. ================================= ========= ======== ============ ==========
  165. Lookup Type PostGIS Oracle MySQL [#]_ SpatiaLite
  166. ================================= ========= ======== ============ ==========
  167. :lookup:`bbcontains` X X X
  168. :lookup:`bboverlaps` X X X
  169. :lookup:`contained` X X X
  170. :lookup:`contains <gis-contains>` X X X X
  171. :lookup:`contains_properly` X
  172. :lookup:`coveredby` X X
  173. :lookup:`covers` X X
  174. :lookup:`crosses` X X
  175. :lookup:`disjoint` X X X X
  176. :lookup:`distance_gt` X X X
  177. :lookup:`distance_gte` X X X
  178. :lookup:`distance_lt` X X X
  179. :lookup:`distance_lte` X X X
  180. :lookup:`dwithin` X X
  181. :lookup:`equals` X X X X
  182. :lookup:`exact` X X X X
  183. :lookup:`intersects` X X X X
  184. :lookup:`overlaps` X X X X
  185. :lookup:`relate` X X X
  186. :lookup:`same_as` X X X X
  187. :lookup:`touches` X X X X
  188. :lookup:`within` X X X X
  189. :lookup:`left` X
  190. :lookup:`right` X
  191. :lookup:`overlaps_left` X
  192. :lookup:`overlaps_right` X
  193. :lookup:`overlaps_above` X
  194. :lookup:`overlaps_below` X
  195. :lookup:`strictly_above` X
  196. :lookup:`strictly_below` X
  197. ================================= ========= ======== ============ ==========
  198. .. _geoqueryset-method-compatibility:
  199. ``GeoQuerySet`` Methods
  200. -----------------------
  201. The following table provides a summary of what :class:`GeoQuerySet` methods
  202. are available on each spatial backend. Please note that MySQL does not
  203. support any of these methods, and is thus excluded from the table.
  204. ==================================== ======= ====== ==========
  205. Method PostGIS Oracle SpatiaLite
  206. ==================================== ======= ====== ==========
  207. :meth:`GeoQuerySet.area` X X X
  208. :meth:`GeoQuerySet.centroid` X X X
  209. :meth:`GeoQuerySet.collect` X (from v3.0)
  210. :meth:`GeoQuerySet.difference` X X X
  211. :meth:`GeoQuerySet.distance` X X X
  212. :meth:`GeoQuerySet.envelope` X X
  213. :meth:`GeoQuerySet.extent` X X (from v3.0)
  214. :meth:`GeoQuerySet.extent3d` X
  215. :meth:`GeoQuerySet.force_rhr` X
  216. :meth:`GeoQuerySet.geohash` X
  217. :meth:`GeoQuerySet.geojson` X X
  218. :meth:`GeoQuerySet.gml` X X X
  219. :meth:`GeoQuerySet.intersection` X X X
  220. :meth:`GeoQuerySet.kml` X X
  221. :meth:`GeoQuerySet.length` X X X
  222. :meth:`GeoQuerySet.make_line` X
  223. :meth:`GeoQuerySet.mem_size` X
  224. :meth:`GeoQuerySet.num_geom` X X X
  225. :meth:`GeoQuerySet.num_points` X X X
  226. :meth:`GeoQuerySet.perimeter` X X
  227. :meth:`GeoQuerySet.point_on_surface` X X X
  228. :meth:`GeoQuerySet.reverse_geom` X X
  229. :meth:`GeoQuerySet.scale` X X
  230. :meth:`GeoQuerySet.snap_to_grid` X
  231. :meth:`GeoQuerySet.svg` X X
  232. :meth:`GeoQuerySet.sym_difference` X X X
  233. :meth:`GeoQuerySet.transform` X X X
  234. :meth:`GeoQuerySet.translate` X X
  235. :meth:`GeoQuerySet.union` X X X
  236. :meth:`GeoQuerySet.unionagg` X X X
  237. ==================================== ======= ====== ==========
  238. .. rubric:: Footnotes
  239. .. [#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).
  240. .. [#fnewkb] *See* `PostGIS EWKB, EWKT and Canonical Forms <http://postgis.net/docs/manual-1.5/ch04.html#EWKB_EWKT>`_, PostGIS documentation at Ch. 4.1.2.
  241. .. [#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).
  242. .. [#fndistsphere15] *See* `PostGIS 1.5 documentation <http://postgis.net/docs/manual-1.5/ST_Distance_Sphere.html>`_ on ``ST_distance_sphere``.
  243. .. [#fnmysqlidx] *See* `Creating Spatial Indexes <http://dev.mysql.com/doc/refman/5.6/en/creating-spatial-indexes.html>`_
  244. in the MySQL Reference Manual:
  245. For MyISAM tables, ``SPATIAL INDEX`` creates an R-tree index. For storage
  246. engines that support nonspatial indexing of spatial columns, the engine
  247. creates a B-tree index. A B-tree index on spatial values will be useful
  248. for exact-value lookups, but not for range scans.
  249. .. [#] Refer :ref:`mysql-spatial-limitations` section for more details.