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