GeoDjango Database APILink para este cabeçalho

Spatial BackendsLink para este cabeçalho

GeoDjango currently provides the following spatial database backends:

  • django.contrib.gis.db.backends.postgis

  • django.contrib.gis.db.backends.mysql

  • django.contrib.gis.db.backends.oracle

  • django.contrib.gis.db.backends.spatialite

MySQL Spatial LimitationsLink para este cabeçalho

MySQL’s spatial extensions only support bounding box operations (what MySQL calls minimum bounding rectangles, or MBR). Specifically, MySQL does not conform to the OGC standard:

Currently, MySQL does not implement these functions [Contains, Crosses, Disjoint, Intersects, Overlaps, Touches, Within] according to the specification. Those that are implemented return the same result as the corresponding MBR-based functions.

In other words, while spatial lookups such as contains are available in GeoDjango when using MySQL, the results returned are really equivalent to what would be returned when using bbcontains on a different spatial backend.

Raster SupportLink para este cabeçalho

RasterField is currently only implemented for the PostGIS backend. Spatial queries (such as lookups and distance) are not yet available for raster fields.

Creating and Saving Models with Geometry FieldsLink para este cabeçalho

Here is an example of how to create a geometry object (assuming the Zipcode model):

Code
>>> from zipcode.models import Zipcode
>>> z = Zipcode(code=77096, poly='POLYGON(( 10 10, 10 20, 20 20, 20 15, 10 10))')
>>> z.save()

GEOSGeometry objects may also be used to save geometric models:

Code
>>> from django.contrib.gis.geos import GEOSGeometry
>>> poly = GEOSGeometry('POLYGON(( 10 10, 10 20, 20 20, 20 15, 10 10))')
>>> z = Zipcode(code=77096, poly=poly)
>>> z.save()

Moreover, if the GEOSGeometry is in a different coordinate system (has a different SRID value) than that of the field, then it will be implicitly transformed into the SRID of the model’s field, using the spatial database’s transform procedure:

Code
>>> poly_3084 = GEOSGeometry('POLYGON(( 10 10, 10 20, 20 20, 20 15, 10 10))', srid=3084)  # SRID 3084 is 'NAD83(HARN) / Texas Centric Lambert Conformal'
>>> z = Zipcode(code=78212, poly=poly_3084)
>>> z.save()
>>> from django.db import connection
>>> print(connection.queries[-1]['sql']) # printing the last SQL statement executed (requires DEBUG=True)
INSERT INTO "geoapp_zipcode" ("code", "poly") VALUES (78212, ST_Transform(ST_GeomFromWKB('\\001 ... ', 3084), 4326))

Thus, geometry parameters may be passed in using the GEOSGeometry object, WKT (Well Known Text [1]), HEXEWKB (PostGIS specific – a WKB geometry in hexadecimal [2]), and GeoJSON [3] (requires GDAL). Essentially, if the input is not a GEOSGeometry object, the geometry field will attempt to create a GEOSGeometry instance from the input.

For more information creating GEOSGeometry objects, refer to the GEOS tutorial.

Creating and Saving Models with Raster FieldsLink para este cabeçalho

When creating raster models, the raster field will implicitly convert the input into a GDALRaster using lazy-evaluation. The raster field will therefore accept any input that is accepted by the GDALRaster constructor.

Here is an example of how to create a raster object from a raster file volcano.tif (assuming the Elevation model):

Code
>>> from elevation.models import Elevation
>>> dem = Elevation(name='Volcano', rast='/path/to/raster/volcano.tif')
>>> dem.save()

GDALRaster objects may also be used to save raster models:

Code
>>> from django.contrib.gis.gdal import GDALRaster
>>> rast = GDALRaster({'width': 10, 'height': 10, 'name': 'Canyon', 'srid': 4326,
...                    'scale': [0.1, -0.1], 'bands': [{"data": range(100)}]})
>>> dem = Elevation(name='Canyon', rast=rast)
>>> dem.save()

Note that this equivalent to:

Code
>>> dem = Elevation.objects.create(
...     name='Canyon',
...     rast={'width': 10, 'height': 10, 'name': 'Canyon', 'srid': 4326,
...           'scale': [0.1, -0.1], 'bands': [{"data": range(100)}]},
... )

Spatial LookupsLink para este cabeçalho

GeoDjango’s lookup types may be used with any manager method like filter(), exclude(), etc. However, the lookup types unique to GeoDjango are only available on geometry fields. Filters on ‘normal’ fields (e.g. CharField) may be chained with those on geographic fields. Thus, geographic queries take the following general form (assuming the Zipcode model used in the GeoDjango Model API):

Code
>>> qs = Zipcode.objects.filter(<field>__<lookup_type>=<parameter>)
>>> qs = Zipcode.objects.exclude(...)

Por exemplo:

Code
>>> qs = Zipcode.objects.filter(poly__contains=pnt)

In this case, poly is the geographic field, contains is the spatial lookup type, and pnt is the parameter (which may be a GEOSGeometry object or a string of GeoJSON , WKT, or HEXEWKB).

A complete reference can be found in the spatial lookup reference.

Distance QueriesLink para este cabeçalho

IntroduçãoLink para este cabeçalho

Distance calculations with spatial data is tricky because, unfortunately, the Earth is not flat. Some distance queries with fields in a geographic coordinate system may have to be expressed differently because of limitations in PostGIS. Please see the Selecting an SRID section in the GeoDjango Model API documentation for more details.

Distance LookupsLink para este cabeçalho

Availability: PostGIS, Oracle, SpatiaLite

The following distance lookups are available:

Distance lookups take a tuple parameter comprising:

  1. A geometry to base calculations from; and

  2. A number or Distance object containing the distance.

If a Distance object is used, it may be expressed in any units (the SQL generated will use units converted to those of the field); otherwise, numeric parameters are assumed to be in the units of the field.

For example, let’s say we have a SouthTexasCity model (from the GeoDjango distance tests ) on a projected coordinate system valid for cities in southern Texas:

Code
from django.contrib.gis.db import models

class SouthTexasCity(models.Model):
    name = models.CharField(max_length=30)
    # A projected coordinate system (only valid for South Texas!)
    # is used, units are in meters.
    point = models.PointField(srid=32140)

Then distance queries may be performed as follows:

Code
>>> from django.contrib.gis.geos import GEOSGeometry
>>> from django.contrib.gis.measure import D # ``D`` is a shortcut for ``Distance``
>>> from geoapp.models import SouthTexasCity
# Distances will be calculated from this point, which does not have to be projected.
>>> pnt = GEOSGeometry('POINT(-96.876369 29.905320)', srid=4326)
# If numeric parameter, units of field (meters in this case) are assumed.
>>> qs = SouthTexasCity.objects.filter(point__distance_lte=(pnt, 7000))
# Find all Cities within 7 km, > 20 miles away, and > 100 chains away (an obscure unit)
>>> qs = SouthTexasCity.objects.filter(point__distance_lte=(pnt, D(km=7)))
>>> qs = SouthTexasCity.objects.filter(point__distance_gte=(pnt, D(mi=20)))
>>> qs = SouthTexasCity.objects.filter(point__distance_gte=(pnt, D(chain=100)))

Compatibility TablesLink para este cabeçalho

Spatial LookupsLink para este cabeçalho

The following table provides a summary of what spatial lookups are available for each spatial database backend.

Tipo de filtro

PostGIS

Oracle

MySQL [6]

SpatiaLite

bbcontains

X

X

X

bboverlaps

X

X

X

contained

X

X

X

contains

X

X

X

X

contains_properly

X

coveredby

X

X

covers

X

X

crosses

X

X

disjoint

X

X

X

X

distance_gt

X

X

X

distance_gte

X

X

X

distance_lt

X

X

X

distance_lte

X

X

X

dwithin

X

X

equals

X

X

X

X

exact

X

X

X

X

intersects

X

X

X

X

overlaps

X

X

X

X

relate

X

X

X

same_as

X

X

X

X

touches

X

X

X

X

within

X

X

X

X

left

X

right

X

overlaps_left

X

overlaps_right

X

overlaps_above

X

overlaps_below

X

strictly_above

X

strictly_below

X

funções de banco de dadosLink para este cabeçalho

A tabela seguinte provê uma lista de quais funções geográficas específicas do banco de dados estão disponíveis em cada “backend” espacial.

Função

PostGIS

Oracle

MySQL

SpatiaLite

Area

X

X

X

X

AsGeoJSON

X

X

AsGML

X

X

AsKML

X

X

AsSVG

X

X

BoundingCircle

X

Centroid

X

X

X

X

Difference

X

X

X

Distance

X

X

X (≥ 5.6.1)

X

Envelope

X

X

X

ForceRHR

X

GeoHash

X

Intersection

X

X

X

Length

X

X

X

X

MemSize

X

NumGeometries

X

X

X

X

NumPoints

X

X

X

X

Perimeter

X

X

X (≥ 4.0)

PointOnSurface

X

X

X

Reverse

X

X

X (≥ 4.0)

Scale

X

X

SnapToGrid

X

X (≥ 3.1)

SymDifference

X

X

X

Transform

X

X

X

Translate

X

X

Union

X

X

X (≥ 5.6.1)

X

Funções de AgregaçãoLink para este cabeçalho

A tabela seguinte provê uma lista de quais funções de agregação geográficas específicas do banco de dados estão disponíveis em cada “backend” espacial. Por favor note que o MySQL não suporta qualquer destas agragações, e portanto está excluído da tabela.

Agregação

PostGIS

Oracle

SpatiaLite

Collect

X

(a partir da v3.0)

Extent

X

X

(a partir da v3.0)

Extent3D

X

MakeLine

X

Union

X

X

X

Notas de rodapé