db-api.txt 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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. .. _mysql-spatial-limitations:
  15. MySQL Spatial Limitations
  16. -------------------------
  17. Django supports spatial functions operating on real geometries available in
  18. modern MySQL versions. However, the spatial functions are not as rich as other
  19. backends like PostGIS.
  20. Raster Support
  21. --------------
  22. ``RasterField`` is currently only implemented for the PostGIS backend. Spatial
  23. lookups are available for raster fields, but spatial database functions and
  24. aggregates aren't implemented for raster fields.
  25. Creating and Saving Models with Geometry Fields
  26. ===============================================
  27. Here is an example of how to create a geometry object (assuming the ``Zipcode``
  28. model):
  29. .. code-block:: pycon
  30. >>> from zipcode.models import Zipcode
  31. >>> z = Zipcode(code=77096, poly="POLYGON(( 10 10, 10 20, 20 20, 20 15, 10 10))")
  32. >>> z.save()
  33. :class:`~django.contrib.gis.geos.GEOSGeometry` objects may also be used to save geometric models:
  34. .. code-block:: pycon
  35. >>> from django.contrib.gis.geos import GEOSGeometry
  36. >>> poly = GEOSGeometry("POLYGON(( 10 10, 10 20, 20 20, 20 15, 10 10))")
  37. >>> z = Zipcode(code=77096, poly=poly)
  38. >>> z.save()
  39. Moreover, if the ``GEOSGeometry`` is in a different coordinate system (has a
  40. different SRID value) than that of the field, then it will be implicitly
  41. transformed into the SRID of the model's field, using the spatial database's
  42. transform procedure:
  43. .. code-block:: pycon
  44. >>> poly_3084 = GEOSGeometry(
  45. ... "POLYGON(( 10 10, 10 20, 20 20, 20 15, 10 10))", srid=3084
  46. ... ) # SRID 3084 is 'NAD83(HARN) / Texas Centric Lambert Conformal'
  47. >>> z = Zipcode(code=78212, poly=poly_3084)
  48. >>> z.save()
  49. >>> from django.db import connection
  50. >>> print(
  51. ... connection.queries[-1]["sql"]
  52. ... ) # printing the last SQL statement executed (requires DEBUG=True)
  53. INSERT INTO "geoapp_zipcode" ("code", "poly") VALUES (78212, ST_Transform(ST_GeomFromWKB('\\001 ... ', 3084), 4326))
  54. Thus, geometry parameters may be passed in using the ``GEOSGeometry`` object, WKT
  55. (Well Known Text [#fnwkt]_), HEXEWKB (PostGIS specific -- a WKB geometry in
  56. hexadecimal [#fnewkb]_), and GeoJSON (see :rfc:`7946`). Essentially, if the
  57. input is not a ``GEOSGeometry`` object, the geometry field will attempt to
  58. create a ``GEOSGeometry`` instance from the input.
  59. For more information creating :class:`~django.contrib.gis.geos.GEOSGeometry`
  60. objects, refer to the :ref:`GEOS tutorial <geos-tutorial>`.
  61. .. _creating-and-saving-raster-models:
  62. Creating and Saving Models with Raster Fields
  63. =============================================
  64. When creating raster models, the raster field will implicitly convert the input
  65. into a :class:`~django.contrib.gis.gdal.GDALRaster` using lazy-evaluation.
  66. The raster field will therefore accept any input that is accepted by the
  67. :class:`~django.contrib.gis.gdal.GDALRaster` constructor.
  68. Here is an example of how to create a raster object from a raster file
  69. ``volcano.tif`` (assuming the ``Elevation`` model):
  70. .. code-block:: pycon
  71. >>> from elevation.models import Elevation
  72. >>> dem = Elevation(name="Volcano", rast="/path/to/raster/volcano.tif")
  73. >>> dem.save()
  74. :class:`~django.contrib.gis.gdal.GDALRaster` objects may also be used to save
  75. raster models:
  76. .. code-block:: pycon
  77. >>> from django.contrib.gis.gdal import GDALRaster
  78. >>> rast = GDALRaster(
  79. ... {
  80. ... "width": 10,
  81. ... "height": 10,
  82. ... "name": "Canyon",
  83. ... "srid": 4326,
  84. ... "scale": [0.1, -0.1],
  85. ... "bands": [{"data": range(100)}],
  86. ... }
  87. ... )
  88. >>> dem = Elevation(name="Canyon", rast=rast)
  89. >>> dem.save()
  90. Note that this equivalent to:
  91. .. code-block:: pycon
  92. >>> dem = Elevation.objects.create(
  93. ... name="Canyon",
  94. ... rast={
  95. ... "width": 10,
  96. ... "height": 10,
  97. ... "name": "Canyon",
  98. ... "srid": 4326,
  99. ... "scale": [0.1, -0.1],
  100. ... "bands": [{"data": range(100)}],
  101. ... },
  102. ... )
  103. .. _spatial-lookups-intro:
  104. Spatial Lookups
  105. ===============
  106. GeoDjango's lookup types may be used with any manager method like
  107. ``filter()``, ``exclude()``, etc. However, the lookup types unique to
  108. GeoDjango are only available on spatial fields.
  109. Filters on 'normal' fields (e.g. :class:`~django.db.models.CharField`)
  110. may be chained with those on geographic fields. Geographic lookups accept
  111. geometry and raster input on both sides and input types can be mixed freely.
  112. The general structure of geographic lookups is described below. A complete
  113. reference can be found in the :ref:`spatial lookup reference<spatial-lookups>`.
  114. Geometry Lookups
  115. ----------------
  116. Geographic queries with geometries take the following general form (assuming
  117. the ``Zipcode`` model used in the :doc:`model-api`):
  118. .. code-block:: text
  119. >>> qs = Zipcode.objects.filter(<field>__<lookup_type>=<parameter>)
  120. >>> qs = Zipcode.objects.exclude(...)
  121. For example:
  122. .. code-block:: pycon
  123. >>> qs = Zipcode.objects.filter(poly__contains=pnt)
  124. >>> qs = Elevation.objects.filter(poly__contains=rst)
  125. In this case, ``poly`` is the geographic field, :lookup:`contains <gis-contains>`
  126. is the spatial lookup type, ``pnt`` is the parameter (which may be a
  127. :class:`~django.contrib.gis.geos.GEOSGeometry` object or a string of
  128. GeoJSON , WKT, or HEXEWKB), and ``rst`` is a
  129. :class:`~django.contrib.gis.gdal.GDALRaster` object.
  130. .. _spatial-lookup-raster:
  131. Raster Lookups
  132. --------------
  133. The raster lookup syntax is similar to the syntax for geometries. The only
  134. difference is that a band index can be specified as additional input. If no band
  135. index is specified, the first band is used by default (index ``0``). In that
  136. case the syntax is identical to the syntax for geometry lookups.
  137. To specify the band index, an additional parameter can be specified on both
  138. sides of the lookup. On the left hand side, the double underscore syntax is
  139. used to pass a band index. On the right hand side, a tuple of the raster and
  140. band index can be specified.
  141. This results in the following general form for lookups involving rasters
  142. (assuming the ``Elevation`` model used in the :doc:`model-api`):
  143. .. code-block:: text
  144. >>> qs = Elevation.objects.filter(<field>__<lookup_type>=<parameter>)
  145. >>> qs = Elevation.objects.filter(<field>__<band_index>__<lookup_type>=<parameter>)
  146. >>> qs = Elevation.objects.filter(<field>__<lookup_type>=(<raster_input, <band_index>)
  147. For example:
  148. .. code-block:: pycon
  149. >>> qs = Elevation.objects.filter(rast__contains=geom)
  150. >>> qs = Elevation.objects.filter(rast__contains=rst)
  151. >>> qs = Elevation.objects.filter(rast__1__contains=geom)
  152. >>> qs = Elevation.objects.filter(rast__contains=(rst, 1))
  153. >>> qs = Elevation.objects.filter(rast__1__contains=(rst, 1))
  154. On the left hand side of the example, ``rast`` is the geographic raster field
  155. and :lookup:`contains <gis-contains>` is the spatial lookup type. On the right
  156. hand side, ``geom`` is a geometry input and ``rst`` is a
  157. :class:`~django.contrib.gis.gdal.GDALRaster` object. The band index defaults to
  158. ``0`` in the first two queries and is set to ``1`` on the others.
  159. While all spatial lookups can be used with raster objects on both sides, not all
  160. underlying operators natively accept raster input. For cases where the operator
  161. expects geometry input, the raster is automatically converted to a geometry.
  162. It's important to keep this in mind when interpreting the lookup results.
  163. The type of raster support is listed for all lookups in the :ref:`compatibility
  164. table <spatial-lookup-compatibility>`. Lookups involving rasters are currently
  165. only available for the PostGIS backend.
  166. .. _distance-queries:
  167. Distance Queries
  168. ================
  169. Introduction
  170. ------------
  171. Distance calculations with spatial data is tricky because, unfortunately,
  172. the Earth is not flat. Some distance queries with fields in a geographic
  173. coordinate system may have to be expressed differently because of
  174. limitations in PostGIS. Please see the :ref:`selecting-an-srid` section
  175. in the :doc:`model-api` documentation for more details.
  176. .. _distance-lookups-intro:
  177. Distance Lookups
  178. ----------------
  179. *Availability*: PostGIS, MariaDB, MySQL, Oracle, SpatiaLite, PGRaster (Native)
  180. The following distance lookups are available:
  181. * :lookup:`distance_lt`
  182. * :lookup:`distance_lte`
  183. * :lookup:`distance_gt`
  184. * :lookup:`distance_gte`
  185. * :lookup:`dwithin` (except MariaDB and MySQL)
  186. .. note::
  187. For *measuring*, rather than querying on distances, use the
  188. :class:`~django.contrib.gis.db.models.functions.Distance` function.
  189. Distance lookups take a tuple parameter comprising:
  190. #. A geometry or raster to base calculations from; and
  191. #. A number or :class:`~django.contrib.gis.measure.Distance` object containing the distance.
  192. If a :class:`~django.contrib.gis.measure.Distance` object is used,
  193. it may be expressed in any units (the SQL generated will use units
  194. converted to those of the field); otherwise, numeric parameters are assumed
  195. to be in the units of the field.
  196. .. note::
  197. In PostGIS, ``ST_Distance_Sphere`` does *not* limit the geometry types
  198. geographic distance queries are performed with. [#fndistsphere15]_ However,
  199. these queries may take a long time, as great-circle distances must be
  200. calculated on the fly for *every* row in the query. This is because the
  201. spatial index on traditional geometry fields cannot be used.
  202. For much better performance on WGS84 distance queries, consider using
  203. :ref:`geography columns <geography-type>` in your database instead because
  204. they are able to use their spatial index in distance queries.
  205. You can tell GeoDjango to use a geography column by setting ``geography=True``
  206. in your field definition.
  207. For example, let's say we have a ``SouthTexasCity`` model (from the
  208. :source:`GeoDjango distance tests <tests/gis_tests/distapp/models.py>` ) on a
  209. *projected* coordinate system valid for cities in southern Texas::
  210. from django.contrib.gis.db import models
  211. class SouthTexasCity(models.Model):
  212. name = models.CharField(max_length=30)
  213. # A projected coordinate system (only valid for South Texas!)
  214. # is used, units are in meters.
  215. point = models.PointField(srid=32140)
  216. Then distance queries may be performed as follows:
  217. .. code-block:: pycon
  218. >>> from django.contrib.gis.geos import GEOSGeometry
  219. >>> from django.contrib.gis.measure import D # ``D`` is a shortcut for ``Distance``
  220. >>> from geoapp.models import SouthTexasCity
  221. # Distances will be calculated from this point, which does not have to be projected.
  222. >>> pnt = GEOSGeometry("POINT(-96.876369 29.905320)", srid=4326)
  223. # If numeric parameter, units of field (meters in this case) are assumed.
  224. >>> qs = SouthTexasCity.objects.filter(point__distance_lte=(pnt, 7000))
  225. # Find all Cities within 7 km, > 20 miles away, and > 100 chains away (an obscure unit)
  226. >>> qs = SouthTexasCity.objects.filter(point__distance_lte=(pnt, D(km=7)))
  227. >>> qs = SouthTexasCity.objects.filter(point__distance_gte=(pnt, D(mi=20)))
  228. >>> qs = SouthTexasCity.objects.filter(point__distance_gte=(pnt, D(chain=100)))
  229. Raster queries work the same way by replacing the geometry field ``point`` with
  230. a raster field, or the ``pnt`` object with a raster object, or both. To specify
  231. the band index of a raster input on the right hand side, a 3-tuple can be
  232. passed to the lookup as follows:
  233. .. code-block:: pycon
  234. >>> qs = SouthTexasCity.objects.filter(point__distance_gte=(rst, 2, D(km=7)))
  235. Where the band with index 2 (the third band) of the raster ``rst`` would be
  236. used for the lookup.
  237. .. _compatibility-table:
  238. Compatibility Tables
  239. ====================
  240. .. _spatial-lookup-compatibility:
  241. Spatial Lookups
  242. ---------------
  243. The following table provides a summary of what spatial lookups are available
  244. for each spatial database backend. The PostGIS Raster (PGRaster) lookups are
  245. divided into the three categories described in the :ref:`raster lookup details
  246. <spatial-lookup-raster>`: native support ``N``, bilateral native support ``B``,
  247. and geometry conversion support ``C``.
  248. ================================= ========= ======== ========== ============ ========== ========
  249. Lookup Type PostGIS Oracle MariaDB MySQL [#]_ SpatiaLite PGRaster
  250. ================================= ========= ======== ========== ============ ========== ========
  251. :lookup:`bbcontains` X X X X N
  252. :lookup:`bboverlaps` X X X X N
  253. :lookup:`contained` X X X X N
  254. :lookup:`contains <gis-contains>` X X X X X B
  255. :lookup:`contains_properly` X B
  256. :lookup:`coveredby` X X X X B
  257. :lookup:`covers` X X X X B
  258. :lookup:`crosses` X X X X C
  259. :lookup:`disjoint` X X X X X B
  260. :lookup:`distance_gt` X X X X X N
  261. :lookup:`distance_gte` X X X X X N
  262. :lookup:`distance_lt` X X X X X N
  263. :lookup:`distance_lte` X X X X X N
  264. :lookup:`dwithin` X X X B
  265. :lookup:`equals` X X X X X C
  266. :lookup:`exact <same_as>` X X X X X B
  267. :lookup:`intersects` X X X X X B
  268. :lookup:`isempty` X
  269. :lookup:`isvalid` X X X X
  270. :lookup:`overlaps` X X X X X B
  271. :lookup:`relate` X X X X C
  272. :lookup:`same_as` X X X X X B
  273. :lookup:`touches` X X X X X B
  274. :lookup:`within` X X X X X B
  275. :lookup:`left` X C
  276. :lookup:`right` X C
  277. :lookup:`overlaps_left` X B
  278. :lookup:`overlaps_right` X B
  279. :lookup:`overlaps_above` X C
  280. :lookup:`overlaps_below` X C
  281. :lookup:`strictly_above` X C
  282. :lookup:`strictly_below` X C
  283. ================================= ========= ======== ========== ============ ========== ========
  284. .. _database-functions-compatibility:
  285. Database functions
  286. ------------------
  287. The following table provides a summary of what geography-specific database
  288. functions are available on each spatial backend.
  289. .. currentmodule:: django.contrib.gis.db.models.functions
  290. ==================================== ======= ============== ============ =========== =================
  291. Function PostGIS Oracle MariaDB MySQL SpatiaLite
  292. ==================================== ======= ============== ============ =========== =================
  293. :class:`Area` X X X X X
  294. :class:`AsGeoJSON` X X X X X
  295. :class:`AsGML` X X X
  296. :class:`AsKML` X X
  297. :class:`AsSVG` X X
  298. :class:`AsWKB` X X X X X
  299. :class:`AsWKT` X X X X X
  300. :class:`Azimuth` X X (LWGEOM/RTTOPO)
  301. :class:`BoundingCircle` X X X (≥ 5.1)
  302. :class:`Centroid` X X X X X
  303. :class:`ClosestPoint` X X
  304. :class:`Difference` X X X X X
  305. :class:`Distance` X X X X X
  306. :class:`Envelope` X X X X X
  307. :class:`ForcePolygonCW` X X
  308. :class:`FromWKB` X X X X X
  309. :class:`FromWKT` X X X X X
  310. :class:`GeoHash` X X X (LWGEOM/RTTOPO)
  311. :class:`GeometryDistance` X
  312. :class:`Intersection` X X X X X
  313. :class:`IsEmpty` X
  314. :class:`IsValid` X X X X
  315. :class:`Length` X X X X X
  316. :class:`LineLocatePoint` X X
  317. :class:`MakeValid` X X (LWGEOM/RTTOPO)
  318. :class:`MemSize` X
  319. :class:`NumGeometries` X X X X X
  320. :class:`NumPoints` X X X X X
  321. :class:`Perimeter` X X X
  322. :class:`PointOnSurface` X X X X
  323. :class:`Reverse` X X X
  324. :class:`Scale` X X
  325. :class:`SnapToGrid` X X
  326. :class:`SymDifference` X X X X X
  327. :class:`Transform` X X X
  328. :class:`Translate` X X
  329. :class:`Union` X X X X X
  330. ==================================== ======= ============== ============ =========== =================
  331. Aggregate Functions
  332. -------------------
  333. The following table provides a summary of what GIS-specific aggregate functions
  334. are available on each spatial backend. Please note that MariaDB does not
  335. support any of these aggregates, and is thus excluded from the table.
  336. .. currentmodule:: django.contrib.gis.db.models
  337. ======================= ======= ====== ============ ==========
  338. Aggregate PostGIS Oracle MySQL SpatiaLite
  339. ======================= ======= ====== ============ ==========
  340. :class:`Collect` X X (≥ 8.0.24) X
  341. :class:`Extent` X X X
  342. :class:`Extent3D` X
  343. :class:`MakeLine` X X
  344. :class:`Union` X X X
  345. ======================= ======= ====== ============ ==========
  346. .. rubric:: Footnotes
  347. .. [#fnwkt] *See* Open Geospatial Consortium, Inc., `OpenGIS Simple Feature Specification For SQL <https://portal.ogc.org/files/?artifact_id=829>`_, Document 99-049 (May 5, 1999), at Ch. 3.2.5, p. 3-11 (SQL Textual Representation of Geometry).
  348. .. [#fnewkb] *See* `PostGIS EWKB, EWKT and Canonical Forms <https://postgis.net/docs/using_postgis_dbmanagement.html#EWKB_EWKT>`_, PostGIS documentation at Ch. 4.1.2.
  349. .. [#fndistsphere15] *See* `PostGIS documentation <https://postgis.net/docs/ST_DistanceSphere.html>`_ on ``ST_DistanceSphere``.
  350. .. [#] Refer :ref:`mysql-spatial-limitations` section for more details.