GeoDjango Database API

Spatial Backends

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 Limitations

Django supports spatial functions operating on real geometries available in modern MySQL versions. However, the spatial functions are not as rich as other backends like PostGIS.

Raster Support

RasterField is currently only implemented for the PostGIS backend. Spatial lookups are available for raster fields, but spatial database functions and aggregates aren’t implemented for raster fields.

Creating and Saving Models with Geometry Fields

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

  1. >>> from zipcode.models import Zipcode
  2. >>> z = Zipcode(code=77096, poly="POLYGON(( 10 10, 10 20, 20 20, 20 15, 10 10))")
  3. >>> z.save()

GEOSGeometry objects may also be used to save geometric models:

  1. >>> from django.contrib.gis.geos import GEOSGeometry
  2. >>> poly = GEOSGeometry("POLYGON(( 10 10, 10 20, 20 20, 20 15, 10 10))")
  3. >>> z = Zipcode(code=77096, poly=poly)
  4. >>> 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:

  1. >>> poly_3084 = GEOSGeometry(
  2. ... "POLYGON(( 10 10, 10 20, 20 20, 20 15, 10 10))", srid=3084
  3. ... ) # SRID 3084 is 'NAD83(HARN) / Texas Centric Lambert Conformal'
  4. >>> z = Zipcode(code=78212, poly=poly_3084)
  5. >>> z.save()
  6. >>> from django.db import connection
  7. >>> print(
  8. ... connection.queries[-1]["sql"]
  9. ... ) # printing the last SQL statement executed (requires DEBUG=True)
  10. 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 (see RFC 7946). 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 Fields

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):

  1. >>> from elevation.models import Elevation
  2. >>> dem = Elevation(name="Volcano", rast="/path/to/raster/volcano.tif")
  3. >>> dem.save()

GDALRaster objects may also be used to save raster models:

  1. >>> from django.contrib.gis.gdal import GDALRaster
  2. >>> rast = GDALRaster(
  3. ... {
  4. ... "width": 10,
  5. ... "height": 10,
  6. ... "name": "Canyon",
  7. ... "srid": 4326,
  8. ... "scale": [0.1, -0.1],
  9. ... "bands": [{"data": range(100)}],
  10. ... }
  11. ... )
  12. >>> dem = Elevation(name="Canyon", rast=rast)
  13. >>> dem.save()

Note that this equivalent to:

  1. >>> dem = Elevation.objects.create(
  2. ... name="Canyon",
  3. ... rast={
  4. ... "width": 10,
  5. ... "height": 10,
  6. ... "name": "Canyon",
  7. ... "srid": 4326,
  8. ... "scale": [0.1, -0.1],
  9. ... "bands": [{"data": range(100)}],
  10. ... },
  11. ... )

Spatial Lookups

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 spatial fields.

Filters on ‘normal’ fields (e.g. CharField) may be chained with those on geographic fields. Geographic lookups accept geometry and raster input on both sides and input types can be mixed freely.

The general structure of geographic lookups is described below. A complete reference can be found in the spatial lookup reference.

Geometry Lookups

Geographic queries with geometries take the following general form (assuming the Zipcode model used in the GeoDjango Model API):

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

For example:

  1. >>> qs = Zipcode.objects.filter(poly__contains=pnt)
  2. >>> qs = Elevation.objects.filter(poly__contains=rst)

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

Raster Lookups

The raster lookup syntax is similar to the syntax for geometries. The only difference is that a band index can be specified as additional input. If no band index is specified, the first band is used by default (index 0). In that case the syntax is identical to the syntax for geometry lookups.

To specify the band index, an additional parameter can be specified on both sides of the lookup. On the left hand side, the double underscore syntax is used to pass a band index. On the right hand side, a tuple of the raster and band index can be specified.

This results in the following general form for lookups involving rasters (assuming the Elevation model used in the GeoDjango Model API):

  1. >>> qs = Elevation.objects.filter(<field>__<lookup_type>=<parameter>)
  2. >>> qs = Elevation.objects.filter(<field>__<band_index>__<lookup_type>=<parameter>)
  3. >>> qs = Elevation.objects.filter(<field>__<lookup_type>=(<raster_input, <band_index>)

For example:

  1. >>> qs = Elevation.objects.filter(rast__contains=geom)
  2. >>> qs = Elevation.objects.filter(rast__contains=rst)
  3. >>> qs = Elevation.objects.filter(rast__1__contains=geom)
  4. >>> qs = Elevation.objects.filter(rast__contains=(rst, 1))
  5. >>> qs = Elevation.objects.filter(rast__1__contains=(rst, 1))

On the left hand side of the example, rast is the geographic raster field and contains is the spatial lookup type. On the right hand side, geom is a geometry input and rst is a GDALRaster object. The band index defaults to 0 in the first two queries and is set to 1 on the others.

While all spatial lookups can be used with raster objects on both sides, not all underlying operators natively accept raster input. For cases where the operator expects geometry input, the raster is automatically converted to a geometry. It’s important to keep this in mind when interpreting the lookup results.

The type of raster support is listed for all lookups in the compatibility table. Lookups involving rasters are currently only available for the PostGIS backend.

Distance Queries

Introduction

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 Lookups

Availability: PostGIS, MariaDB, MySQL, Oracle, SpatiaLite, PGRaster (Native)

The following distance lookups are available:

Note

For measuring, rather than querying on distances, use the Distance function.

Distance lookups take a tuple parameter comprising:

  1. A geometry or raster 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.

Note

In PostGIS, ST_Distance_Sphere does not limit the geometry types geographic distance queries are performed with. [3] However, these queries may take a long time, as great-circle distances must be calculated on the fly for every row in the query. This is because the spatial index on traditional geometry fields cannot be used.

For much better performance on WGS84 distance queries, consider using geography columns in your database instead because they are able to use their spatial index in distance queries. You can tell GeoDjango to use a geography column by setting geography=True in your field definition.

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:

  1. from django.contrib.gis.db import models
  2. class SouthTexasCity(models.Model):
  3. name = models.CharField(max_length=30)
  4. # A projected coordinate system (only valid for South Texas!)
  5. # is used, units are in meters.
  6. point = models.PointField(srid=32140)

Then distance queries may be performed as follows:

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

Raster queries work the same way by replacing the geometry field point with a raster field, or the pnt object with a raster object, or both. To specify the band index of a raster input on the right hand side, a 3-tuple can be passed to the lookup as follows:

  1. >>> qs = SouthTexasCity.objects.filter(point__distance_gte=(rst, 2, D(km=7)))

Where the band with index 2 (the third band) of the raster rst would be used for the lookup.

Compatibility Tables

Spatial Lookups

The following table provides a summary of what spatial lookups are available for each spatial database backend. The PostGIS Raster (PGRaster) lookups are divided into the three categories described in the raster lookup details: native support N, bilateral native support B, and geometry conversion support C.

Lookup TypePostGISOracleMariaDBMySQL [4]SpatiaLitePGRaster
bbcontainsX XXXN
bboverlapsX XXXN
containedX XXXN
containsXXXXXB
contains_properlyX    B
coveredbyXX  XB
coversXX  XB
crossesX XXXC
disjointXXXXXB
distance_gtXXXXXN
distance_gteXXXXXN
distance_ltXXXXXN
distance_lteXXXXXN
dwithinXX  XB
equalsXXXXXC
exactXXXXXB
intersectsXXXXXB
isemptyX     
isvalidXX XX 
overlapsXXXXXB
relateXXX XC
same_asXXXXXB
touchesXXXXXB
withinXXXXXB
leftX    C
rightX    C
overlaps_leftX    B
overlaps_rightX    B
overlaps_aboveX    C
overlaps_belowX    C
strictly_aboveX    C
strictly_belowX    C

Database functions

The following table provides a summary of what geography-specific database functions are available on each spatial backend.

FunctionPostGISOracleMariaDBMySQLSpatiaLite
AreaXXXXX
AsGeoJSONXXXXX
AsGMLXX  X
AsKMLX   X
AsSVGX   X
AsWKBXXXXX
AsWKTXXXXX
AzimuthX   X (LWGEOM/RTTOPO)
BoundingCircleXX   
CentroidXXXXX
DifferenceXXXXX
DistanceXXXXX
EnvelopeXXXXX
ForcePolygonCWX   X
FromWKBXXXXX
FromWKTXXXXX
GeoHashX  XX (LWGEOM/RTTOPO)
IntersectionXXXXX
IsEmptyX    
IsValidXX XX
LengthXXXXX
LineLocatePointX   X
MakeValidX   X (LWGEOM/RTTOPO)
MemSizeX    
NumGeometriesXXXXX
NumPointsXXXXX
PerimeterXX  X
PointOnSurfaceXXX X
ReverseXX  X
ScaleX   X
SnapToGridX   X
SymDifferenceXXXXX
TransformXX  X
TranslateX   X
UnionXXXXX

Aggregate Functions

The following table provides a summary of what GIS-specific aggregate functions are available on each spatial backend. Please note that MySQL does not support any of these aggregates, and is thus excluded from the table.

AggregatePostGISOracleSpatiaLite
CollectX X
ExtentXXX
Extent3DX  
MakeLineX X
UnionXXX

Footnotes

[1]See Open Geospatial Consortium, Inc., OpenGIS Simple Feature Specification For SQL, Document 99-049 (May 5, 1999), at Ch. 3.2.5, p. 3-11 (SQL Textual Representation of Geometry).
[2]See PostGIS EWKB, EWKT and Canonical Forms, PostGIS documentation at Ch. 4.1.2.
[3]See PostGIS documentation on ST_DistanceSphere.
[4]Refer MySQL Spatial Limitations section for more details.