model-api.txt 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. ===================
  2. GeoDjango Model API
  3. ===================
  4. .. module:: django.contrib.gis.db.models
  5. :synopsis: GeoDjango model and field API.
  6. This document explores the details of the GeoDjango Model API. Throughout this
  7. section, we'll be using the following geographic model of a `ZIP code`__ and
  8. of a `Digital Elevation Model`__ as our examples::
  9. from django.contrib.gis.db import models
  10. class Zipcode(models.Model):
  11. code = models.CharField(max_length=5)
  12. poly = models.PolygonField()
  13. class Elevation(models.Model):
  14. name = models.CharField(max_length=100)
  15. rast = models.RasterField()
  16. __ https://en.wikipedia.org/wiki/ZIP_code
  17. __ https://en.wikipedia.org/wiki/Digital_elevation_model
  18. Spatial Field Types
  19. ===================
  20. Spatial fields consist of a series of geometry field types and one raster field
  21. type. Each of the geometry field types correspond to the OpenGIS Simple
  22. Features specification [#fnogc]_. There is no such standard for raster data.
  23. ``GeometryField``
  24. -----------------
  25. .. class:: GeometryField
  26. The base class for geometry fields.
  27. ``PointField``
  28. --------------
  29. .. class:: PointField
  30. Stores a :class:`~django.contrib.gis.geos.Point`.
  31. ``LineStringField``
  32. -------------------
  33. .. class:: LineStringField
  34. Stores a :class:`~django.contrib.gis.geos.LineString`.
  35. ``PolygonField``
  36. ----------------
  37. .. class:: PolygonField
  38. Stores a :class:`~django.contrib.gis.geos.Polygon`.
  39. ``MultiPointField``
  40. -------------------
  41. .. class:: MultiPointField
  42. Stores a :class:`~django.contrib.gis.geos.MultiPoint`.
  43. ``MultiLineStringField``
  44. ------------------------
  45. .. class:: MultiLineStringField
  46. Stores a :class:`~django.contrib.gis.geos.MultiLineString`.
  47. ``MultiPolygonField``
  48. ---------------------
  49. .. class:: MultiPolygonField
  50. Stores a :class:`~django.contrib.gis.geos.MultiPolygon`.
  51. ``GeometryCollectionField``
  52. ---------------------------
  53. .. class:: GeometryCollectionField
  54. Stores a :class:`~django.contrib.gis.geos.GeometryCollection`.
  55. ``RasterField``
  56. ---------------
  57. .. class:: RasterField
  58. Stores a :class:`~django.contrib.gis.gdal.GDALRaster`.
  59. ``RasterField`` is currently only implemented for the PostGIS backend.
  60. Spatial Field Options
  61. =====================
  62. In addition to the regular :ref:`common-model-field-options` available for
  63. Django model fields, spatial fields have the following additional options.
  64. All are optional.
  65. ``srid``
  66. --------
  67. .. attribute:: BaseSpatialField.srid
  68. Sets the SRID [#fnogcsrid]_ (Spatial Reference System Identity) of the geometry field to
  69. the given value. Defaults to 4326 (also known as `WGS84`__, units are in degrees
  70. of longitude and latitude).
  71. __ https://en.wikipedia.org/wiki/WGS84
  72. .. _selecting-an-srid:
  73. Selecting an SRID
  74. ~~~~~~~~~~~~~~~~~
  75. Choosing an appropriate SRID for your model is an important decision that the
  76. developer should consider carefully. The SRID is an integer specifier that
  77. corresponds to the projection system that will be used to interpret the data
  78. in the spatial database. [#fnsrid]_ Projection systems give the context to the
  79. coordinates that specify a location. Although the details of `geodesy`__ are
  80. beyond the scope of this documentation, the general problem is that the earth
  81. is spherical and representations of the earth (e.g., paper maps, web maps)
  82. are not.
  83. Most people are familiar with using latitude and longitude to reference a
  84. location on the earth's surface. However, latitude and longitude are angles,
  85. not distances. In other words, while the shortest path between two points on
  86. a flat surface is a straight line, the shortest path between two points on a curved
  87. surface (such as the earth) is an *arc* of a `great circle`__. [#fnthematic]_ Thus,
  88. additional computation is required to obtain distances in planar units (e.g.,
  89. kilometers and miles). Using a geographic coordinate system may introduce
  90. complications for the developer later on. For example, SpatiaLite does not have
  91. the capability to perform distance calculations between geometries using
  92. geographic coordinate systems, e.g. constructing a query to find all points
  93. within 5 miles of a county boundary stored as WGS84.
  94. [#fndist]_
  95. Portions of the earth's surface may projected onto a two-dimensional, or
  96. Cartesian, plane. Projected coordinate systems are especially convenient
  97. for region-specific applications, e.g., if you know that your database will
  98. only cover geometries in `North Kansas`__, then you may consider using projection
  99. system specific to that region. Moreover, projected coordinate systems are
  100. defined in Cartesian units (such as meters or feet), easing distance
  101. calculations.
  102. .. note::
  103. If you wish to perform arbitrary distance queries using non-point
  104. geometries in WGS84 in PostGIS and you want decent performance, enable the
  105. :attr:`GeometryField.geography` keyword so that :ref:`geography database
  106. type <geography-type>` is used instead.
  107. Additional Resources:
  108. * `spatialreference.org`__: A Django-powered database of spatial reference
  109. systems.
  110. * `The State Plane Coordinate System`__: A website covering the various
  111. projection systems used in the United States. Much of the U.S. spatial
  112. data encountered will be in one of these coordinate systems rather than
  113. in a geographic coordinate system such as WGS84.
  114. __ https://en.wikipedia.org/wiki/Geodesy
  115. __ https://en.wikipedia.org/wiki/Great_circle
  116. __ https://spatialreference.org/ref/epsg/2796/
  117. __ https://spatialreference.org/
  118. __ https://web.archive.org/web/20080302095452/http://welcome.warnercnr.colostate.edu/class_info/nr502/lg3/datums_coordinates/spcs.html
  119. ``spatial_index``
  120. -----------------
  121. .. attribute:: BaseSpatialField.spatial_index
  122. Defaults to ``True``. Creates a spatial index for the given geometry
  123. field.
  124. .. note::
  125. This is different from the ``db_index`` field option because spatial
  126. indexes are created in a different manner than regular database
  127. indexes. Specifically, spatial indexes are typically created using
  128. a variant of the R-Tree, while regular database indexes typically
  129. use B-Trees.
  130. .. _geometry-field-options:
  131. Geometry Field Options
  132. ======================
  133. There are additional options available for Geometry fields. All the following
  134. options are optional.
  135. ``dim``
  136. -------
  137. .. attribute:: GeometryField.dim
  138. This option may be used for customizing the coordinate dimension of the
  139. geometry field. By default, it is set to 2, for representing two-dimensional
  140. geometries. For spatial backends that support it, it may be set to 3 for
  141. three-dimensional support.
  142. .. note::
  143. At this time 3D support is limited to the PostGIS and SpatiaLite backends.
  144. ``geography``
  145. -------------
  146. .. attribute:: GeometryField.geography
  147. If set to ``True``, this option will create a database column of
  148. type geography, rather than geometry. Please refer to the
  149. :ref:`geography type <geography-type>` section below for more
  150. details.
  151. .. note::
  152. Geography support is limited to PostGIS and will force the SRID to be 4326.
  153. .. _geography-type:
  154. Geography Type
  155. ~~~~~~~~~~~~~~
  156. The geography type provides native support for spatial features represented
  157. with geographic coordinates (e.g., WGS84 longitude/latitude). [#fngeography]_
  158. Unlike the plane used by a geometry type, the geography type uses a spherical
  159. representation of its data. Distance and measurement operations
  160. performed on a geography column automatically employ great circle arc
  161. calculations and return linear units. In other words, when ``ST_Distance``
  162. is called on two geographies, a value in meters is returned (as opposed
  163. to degrees if called on a geometry column in WGS84).
  164. Because geography calculations involve more mathematics, only a subset of the
  165. PostGIS spatial lookups are available for the geography type. Practically,
  166. this means that in addition to the :ref:`distance lookups <distance-lookups>`
  167. only the following additional :ref:`spatial lookups <spatial-lookups>` are
  168. available for geography columns:
  169. * :lookup:`bboverlaps`
  170. * :lookup:`coveredby`
  171. * :lookup:`covers`
  172. * :lookup:`intersects`
  173. If you need to use a spatial lookup or aggregate that doesn't support the
  174. geography type as input, you can use the
  175. :class:`~django.db.models.functions.Cast` database function to convert the
  176. geography column to a geometry type in the query::
  177. from django.contrib.gis.db.models import PointField
  178. from django.db.models.functions import Cast
  179. Zipcode.objects.annotate(geom=Cast("geography_field", PointField())).filter(
  180. geom__within=poly
  181. )
  182. For more information, the PostGIS documentation contains a helpful section on
  183. determining `when to use geography data type over geometry data type
  184. <https://postgis.net/docs/using_postgis_dbmanagement.html#PostGIS_GeographyVSGeometry>`_.
  185. .. rubric:: Footnotes
  186. .. [#fnogc] OpenGIS Consortium, Inc., `Simple Feature Specification For SQL <https://www.ogc.org/standard/sfs/>`_.
  187. .. [#fnogcsrid] *See id.* at Ch. 2.3.8, p. 39 (Geometry Values and Spatial Reference Systems).
  188. .. [#fnsrid] Typically, SRID integer corresponds to an EPSG (`European Petroleum Survey Group <https://epsg.org/>`_) identifier. However, it may also be associated with custom projections defined in spatial database's spatial reference systems table.
  189. .. [#fnthematic] Terry A. Slocum, Robert B. McMaster, Fritz C. Kessler, & Hugh H. Howard, *Thematic Cartography and Geographic Visualization* (Prentice Hall, 2nd edition), at Ch. 7.1.3.
  190. .. [#fndist] This limitation does not apply to PostGIS.
  191. .. [#fngeography] Please refer to the `PostGIS Geography Type <https://postgis.net/docs/using_postgis_dbmanagement.html#PostGIS_Geography>`_ documentation for more details.