model-api.txt 9.7 KB

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