model-api.txt 10 KB

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