db-api.txt 15 KB

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