db-api.txt 14 KB

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