# Django 5.2.8 documentation

# GeoDjango modell-API

This document explores the details of the GeoDjango Model API. Throughout this section, we’ll be using the following geographic model of a ZIP code and of a Digital Elevation Model as our examples:

    from django.contrib.gis.db import models

    class Zipcode(models.Model):
        code = models.CharField(max_length=5)
        poly = models.PolygonField()

    class Elevation(models.Model):
        name = models.CharField(max_length=100)
        rast = models.RasterField()

## Spatiala fälttyper

Spatiala fält består av en serie geometriska fälttyper och en rasterfälttyp. Var och en av geometrifälttyperna motsvarar OpenGIS Simple Features-specifikationen [1]. Det finns ingen sådan standard för rasterdata.

### `GeometryField`

class GeometryField

Basklass för geometriska fält.

### `PointField`

class PointField

Lagrar en `Point`.

### `LineStringField`

class LineStringField

Lagrar en `LineString`.

### `PolygonField`

class PolygonField

Lagrar en `Polygon`.

### `MultiPointField`

class MultiPointField

Lagrar en `MultiPoint`.

### `MultiLineStringField`

class MultiLineStringField

Lagrar en `MultiLineString`.

### `MultiPolygonField`

class MultiPolygonField

Lagrar en `MultiPolygon`.

### `GeometryCollectionField`

class GeometryCollectionField

Lagrar en `GeometryCollection`.

### `RasterField`

class RasterField

Lagrar en `GDALRaster`.

`RasterField` är för närvarande endast implementerat för PostGIS backend.

## Alternativ för rumslig fältindelning

Förutom de vanliga Alternativ för fält som finns tillgängliga för Django-modellfält, har spatiala fält följande ytterligare alternativ. Alla är valfria.

### `srid`

BaseSpatialField.srid

Ställer in SRID [2] (Spatial Reference System Identity) för geometrifältet till det angivna värdet. Standardvärdet är 4326 (även känt som WGS84, enheterna är i grader av longitud och latitud).

#### Välja en SRID

Choosing an appropriate SRID for your model is an important decision that the developer should consider carefully. The SRID is an integer specifier that corresponds to the projection system that will be used to interpret the data in the spatial database. [3] Projection systems give the context to the coordinates that specify a location. Although the details of geodesy are beyond the scope of this documentation, the general problem is that the earth is spherical and representations of the earth (e.g., paper maps, web maps) are not.

Most people are familiar with using latitude and longitude to reference a location on the earth’s surface. However, latitude and longitude are angles, not distances. In other words, while the shortest path between two points on a flat surface is a straight line, the shortest path between two points on a curved surface (such as the earth) is an arc of a great circle. [4]

Thus, additional computation is required to obtain distances in planar units (e.g., kilometers and miles). Using a geographic coordinate system may introduce complications for the developer later on. For example, SpatiaLite does not have the capability to perform distance calculations between geometries using geographic coordinate systems, e.g. constructing a query to find all points within 5 miles of a county boundary stored as WGS84. [5]

Portions of the earth’s surface may projected onto a two-dimensional, or Cartesian, plane. Projected coordinate systems are especially convenient for region-specific applications, e.g., if you know that your database will only cover geometries in North Kansas, then you may consider using projection system specific to that region. Moreover, projected coordinate systems are defined in Cartesian units (such as meters or feet), easing distance calculations.

Observera

Om du vill utföra godtyckliga avståndsfrågor med hjälp av icke-punktgeometrier i WGS84 i PostGIS och du vill ha anständig prestanda, aktivera nyckelordet `GeometryField.geography` så att geography database type används istället.

Mer om detta:

- spatialreference.org: En Django-driven databas med rumsliga referenssystem.

- The State Plane Coordinate System: A website covering the various projection systems used in the United States. Much of the U.S. spatial data encountered will be in one of these coordinate systems rather than in a geographic coordinate system such as WGS84.

### `rumsligt_index`

BaseSpatialField.spatial_index

Defaults to `True`. Creates a spatial index for the given geometry field.

Observera

This is different from the `db_index` field option because spatial indexes are created in a different manner than regular database indexes. Specifically, spatial indexes are typically created using a variant of the R-Tree, while regular database indexes typically use B-Trees.

## Alternativ för geometrifält

Det finns ytterligare alternativ tillgängliga för Geometry-fält. Alla följande alternativ är valfria.

### `dim`

GeometryField.dim

This option may be used for customizing the coordinate dimension of the geometry field. By default, it is set to 2, for representing two-dimensional geometries. For spatial backends that support it, it may be set to 3 for three-dimensional support.

Observera

För närvarande är 3D-stödet begränsat till PostGIS- och SpatiaLite-backends.

### `geografi`

GeometryField.geography

If set to `True`, this option will create a database column of type geography, rather than geometry. Please refer to the geography type section below for more details.

Observera

Geografistödet är begränsat till PostGIS och tvingar SRID att vara 4326.

#### Geography-typ

The geography type provides native support for spatial features represented with geographic coordinates (e.g., WGS84 longitude/latitude). [6] Unlike the plane used by a geometry type, the geography type uses a spherical representation of its data. Distance and measurement operations performed on a geography column automatically employ great circle arc calculations and return linear units. In other words, when `ST_Distance` is called on two geographies, a value in meters is returned (as opposed to degrees if called on a geometry column in WGS84).

Eftersom geografiska beräkningar kräver mer matematik är endast en delmängd av PostGIS rumsliga uppslagsord tillgängliga för den geografiska typen. I praktiken innebär detta att utöver distance lookups är endast följande ytterligare spatial lookups tillgängliga för geografiska kolumner:

- `bboverlaps`

- `täckt av`

- `täcken`

- `intersects`

Om du behöver använda en spatial lookup eller aggregat som inte stöder geografin som indata kan du använda databasfunktionen `Cast` för att konvertera geografikolumnen till en geometrityp i frågan:

    from django.contrib.gis.db.models import PointField
    from django.db.models.functions import Cast

    Zipcode.objects.annotate(geom=Cast("geography_field", PointField())).filter(
        geom__within=poly
    )

For more information, the PostGIS documentation contains a helpful section on determining when to use geography data type over geometry data type.

Fotnoter

[1]

OpenGIS Consortium, Inc, Simple Feature Specification For SQL.

[2]

Se id. i kap. 2.3.8, s. 39 (Geometrivärden och rumsliga referenssystem).

[3]

Typically, SRID integer corresponds to an EPSG (European Petroleum Survey Group) identifier. However, it may also be associated with custom projections defined in spatial database’s spatial reference systems table.

[4]

Terry A. Slocum, Robert B. McMaster, Fritz C. Kessler och Hugh H. Howard, Thematic Cartography and Geographic Visualization (Prentice Hall, 2:a upplagan), kapitel 7.1.3.

[5]

Denna begränsning gäller inte för PostGIS.

[6]

Mer information finns i dokumentationen PostGIS Geography Type.