db-api.txt 15 KB

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