model-api.txt 9.4 KB

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