model-api.txt 10 KB

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