GIS QuerySet API Reference

空间查找

The spatial lookups in this section are available for GeometryField and RasterField.

For an introduction, see the spatial lookups introduction. For an overview of what lookups are compatible with a particular spatial backend, refer to the spatial lookup compatibility table.

Lookups with rasters

All examples in the reference below are given for geometry fields and inputs, but the lookups can be used the same way with rasters on both sides. Whenever a lookup doesn’t support raster input, the input is automatically converted to a geometry where necessary using the ST_Polygon function. See also the introduction to raster lookups.

The database operators used by the lookups can be divided into three categories:

  • Native raster support N: the operator accepts rasters natively on both sides of the lookup, and raster input can be mixed with geometry inputs.
  • Bilateral raster support B: the operator supports rasters only if both sides of the lookup receive raster inputs. Raster data is automatically converted to geometries for mixed lookups.
  • Geometry conversion support C. The lookup does not have native raster support, all raster data is automatically converted to geometries.

The examples below show the SQL equivalent for the lookups in the different types of raster support. The same pattern applies to all spatial lookups.

Case查找SQL Equivalent
N, Brastcontains=rstST_Contains(rast, rst)
N, Brast1contains=(rst, 2)ST_Contains(rast, 1, rst, 2)
B, Crastcontains=geomST_Contains(ST_Polygon(rast), geom)
B, Crast1contains=geomST_Contains(ST_Polygon(rast, 1), geom)
B, Cpolycontains=rstST_Contains(poly, ST_Polygon(rst))
B, Cpolycontains=(rst, 1)ST_Contains(poly, ST_Polygon(rst, 1))
Crastcrosses=rstST_Crosses(ST_Polygon(rast), ST_Polygon(rst))
Crast1crosses=(rst, 2)ST_Crosses(ST_Polygon(rast, 1), ST_Polygon(rst, 2))
Crastcrosses=geomST_Crosses(ST_Polygon(rast), geom)
Cpoly__crosses=rstST_Crosses(poly, ST_Polygon(rst))

Spatial lookups with rasters are only supported for PostGIS backends (denominated as PGRaster in this section).

bbcontains

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

Tests if the geometry or raster field’s bounding box completely contains the lookup geometry’s bounding box.

举例:

  1. Zipcode.objects.filter(poly__bbcontains=geom)
BackendSQL Equivalent
PostGISpoly ~ geom
MariaDBMBRContains(poly, geom)
MySQLMBRContains(poly, geom)
SpatiaLiteMbrContains(poly, geom)

bboverlaps

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

Tests if the geometry field’s bounding box overlaps the lookup geometry’s bounding box.

举例:

  1. Zipcode.objects.filter(poly__bboverlaps=geom)
BackendSQL Equivalent
PostGISpoly && geom
MariaDBMBROverlaps(poly, geom)
MySQLMBROverlaps(poly, geom)
SpatiaLiteMbrOverlaps(poly, geom)

contained

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

Tests if the geometry field’s bounding box is completely contained by the lookup geometry’s bounding box.

举例:

  1. Zipcode.objects.filter(poly__contained=geom)
BackendSQL Equivalent
PostGISpoly @ geom
MariaDBMBRWithin(poly, geom)
MySQLMBRWithin(poly, geom)
SpatiaLiteMbrWithin(poly, geom)

contains

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

Tests if the geometry field spatially contains the lookup geometry.

举例:

  1. Zipcode.objects.filter(poly__contains=geom)
BackendSQL Equivalent
PostGISST_Contains(poly, geom)
OracleSDO_CONTAINS(poly, geom)
MariaDBST_Contains(poly, geom)
MySQLST_Contains(poly, geom)
SpatiaLiteContains(poly, geom)

contains_properly

Availability: PostGIS, PGRaster (Bilateral)

Returns true if the lookup geometry intersects the interior of the geometry field, but not the boundary (or exterior).

举例:

  1. Zipcode.objects.filter(poly__contains_properly=geom)
BackendSQL Equivalent
PostGISST_ContainsProperly(poly, geom)

coveredby

Availability: PostGIS, Oracle, PGRaster (Bilateral), SpatiaLite

Tests if no point in the geometry field is outside the lookup geometry. [3]

举例:

  1. Zipcode.objects.filter(poly__coveredby=geom)
BackendSQL Equivalent
PostGISST_CoveredBy(poly, geom)
OracleSDO_COVEREDBY(poly, geom)
SpatiaLiteCoveredBy(poly, geom)

covers

Availability: PostGIS, Oracle, PGRaster (Bilateral), SpatiaLite

Tests if no point in the lookup geometry is outside the geometry field. [3]

举例:

  1. Zipcode.objects.filter(poly__covers=geom)
BackendSQL Equivalent
PostGISST_Covers(poly, geom)
OracleSDO_COVERS(poly, geom)
SpatiaLiteCovers(poly, geom)

crosses

Availability: PostGIS, MariaDB, MySQL, SpatiaLite, PGRaster (Conversion)

Tests if the geometry field spatially crosses the lookup geometry.

举例:

  1. Zipcode.objects.filter(poly__crosses=geom)
BackendSQL Equivalent
PostGISST_Crosses(poly, geom)
MariaDBST_Crosses(poly, geom)
MySQLST_Crosses(poly, geom)
SpatiaLiteCrosses(poly, geom)

disjoint

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

Tests if the geometry field is spatially disjoint from the lookup geometry.

举例:

  1. Zipcode.objects.filter(poly__disjoint=geom)
BackendSQL Equivalent
PostGISST_Disjoint(poly, geom)
OracleSDO_GEOM.RELATE(poly, ‘DISJOINT’, geom, 0.05)
MariaDBST_Disjoint(poly, geom)
MySQLST_Disjoint(poly, geom)
SpatiaLiteDisjoint(poly, geom)

equals

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

Tests if the geometry field is spatially equal to the lookup geometry.

举例:

  1. Zipcode.objects.filter(poly__equals=geom)
BackendSQL Equivalent
PostGISST_Equals(poly, geom)
OracleSDO_EQUAL(poly, geom)
MariaDBST_Equals(poly, geom)
MySQLST_Equals(poly, geom)
SpatiaLiteEquals(poly, geom)

exact, same_as

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

Tests if the geometry field is “equal” to the lookup geometry. On Oracle, MySQL, and SpatiaLite, it tests spatial equality, while on PostGIS it tests equality of bounding boxes.

举例:

  1. Zipcode.objects.filter(poly=geom)
BackendSQL Equivalent
PostGISpoly ~= geom
OracleSDO_EQUAL(poly, geom)
MariaDBST_Equals(poly, geom)
MySQLST_Equals(poly, geom)
SpatiaLiteEquals(poly, geom)

intersects

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

Tests if the geometry field spatially intersects the lookup geometry.

举例:

  1. Zipcode.objects.filter(poly__intersects=geom)
BackendSQL Equivalent
PostGISST_Intersects(poly, geom)
OracleSDO_OVERLAPBDYINTERSECT(poly, geom)
MariaDBST_Intersects(poly, geom)
MySQLST_Intersects(poly, geom)
SpatiaLiteIntersects(poly, geom)

isvalid

Availability: MySQL (≥ 5.7.5), PostGIS, Oracle, SpatiaLite

Tests if the geometry is valid.

举例:

  1. Zipcode.objects.filter(poly__isvalid=True)
BackendSQL Equivalent
MySQL, PostGIS, SpatiaLiteST_IsValid(poly)
OracleSDO_GEOM.VALIDATE_GEOMETRY_WITH_CONTEXT(poly, 0.05) = ‘TRUE’

overlaps

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

Tests if the geometry field spatially overlaps the lookup geometry.

BackendSQL Equivalent
PostGISST_Overlaps(poly, geom)
OracleSDO_OVERLAPS(poly, geom)
MariaDBST_Overlaps(poly, geom)
MySQLST_Overlaps(poly, geom)
SpatiaLiteOverlaps(poly, geom)

relate

Availability: PostGIS, MariaDB, Oracle, SpatiaLite, PGRaster (Conversion)

Tests if the geometry field is spatially related to the lookup geometry by the values given in the given pattern. This lookup requires a tuple parameter, (geom, pattern); the form of pattern will depend on the spatial backend:

MariaDB, PostGIS, and SpatiaLite

On these spatial backends the intersection pattern is a string comprising nine characters, which define intersections between the interior, boundary, and exterior of the geometry field and the lookup geometry. The intersection pattern matrix may only use the following characters: 1, 2, T, F, or *. This lookup type allows users to “fine tune” a specific geometric relationship consistent with the DE-9IM model. [1]

Geometry example:

  1. # A tuple lookup parameter is used to specify the geometry and
  2. # the intersection pattern (the pattern here is for 'contains').
  3. Zipcode.objects.filter(poly__relate=(geom, 'T*T***FF*'))

PostGIS and MariaDB SQL equivalent:

  1. SELECT ... WHERE ST_Relate(poly, geom, 'T*T***FF*')

SpatiaLite SQL equivalent:

  1. SELECT ... WHERE Relate(poly, geom, 'T*T***FF*')

Raster example:

  1. Zipcode.objects.filter(poly__relate=(rast, 1, 'T*T***FF*'))
  2. Zipcode.objects.filter(rast__2__relate=(rast, 1, 'T*T***FF*'))

PostGIS SQL equivalent:

  1. SELECT ... WHERE ST_Relate(poly, ST_Polygon(rast, 1), 'T*T***FF*')
  2. SELECT ... WHERE ST_Relate(ST_Polygon(rast, 2), ST_Polygon(rast, 1), 'T*T***FF*')

Oracle

Here the relation pattern is comprised of at least one of the nine relation strings: TOUCH, OVERLAPBDYDISJOINT, OVERLAPBDYINTERSECT, EQUAL, INSIDE, COVEREDBY, CONTAINS, COVERS, ON, and ANYINTERACT. Multiple strings may be combined with the logical Boolean operator OR, for example, 'inside+touch'. [2] The relation strings are case-insensitive.

举例:

  1. Zipcode.objects.filter(poly__relate=(geom, 'anyinteract'))

Oracle SQL equivalent:

  1. SELECT ... WHERE SDO_RELATE(poly, geom, 'anyinteract')

touches

Availability: PostGIS, Oracle, MariaDB, MySQL, SpatiaLite

Tests if the geometry field spatially touches the lookup geometry.

举例:

  1. Zipcode.objects.filter(poly__touches=geom)
BackendSQL Equivalent
PostGISST_Touches(poly, geom)
MariaDBST_Touches(poly, geom)
MySQLST_Touches(poly, geom)
OracleSDO_TOUCH(poly, geom)
SpatiaLiteTouches(poly, geom)

within

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

Tests if the geometry field is spatially within the lookup geometry.

举例:

  1. Zipcode.objects.filter(poly__within=geom)
BackendSQL Equivalent
PostGISST_Within(poly, geom)
MariaDBST_Within(poly, geom)
MySQLST_Within(poly, geom)
OracleSDO_INSIDE(poly, geom)
SpatiaLiteWithin(poly, geom)

left

Availability: PostGIS, PGRaster (Conversion)

Tests if the geometry field’s bounding box is strictly to the left of the lookup geometry’s bounding box.

举例:

  1. Zipcode.objects.filter(poly__left=geom)

PostGIS equivalent:

  1. SELECT ... WHERE poly << geom

right

Availability: PostGIS, PGRaster (Conversion)

Tests if the geometry field’s bounding box is strictly to the right of the lookup geometry’s bounding box.

举例:

  1. Zipcode.objects.filter(poly__right=geom)

PostGIS equivalent:

  1. SELECT ... WHERE poly >> geom

overlaps_left

Availability: PostGIS, PGRaster (Bilateral)

Tests if the geometry field’s bounding box overlaps or is to the left of the lookup geometry’s bounding box.

举例:

  1. Zipcode.objects.filter(poly__overlaps_left=geom)

PostGIS equivalent:

  1. SELECT ... WHERE poly &< geom

overlaps_right

Availability: PostGIS, PGRaster (Bilateral)

Tests if the geometry field’s bounding box overlaps or is to the right of the lookup geometry’s bounding box.

举例:

  1. Zipcode.objects.filter(poly__overlaps_right=geom)

PostGIS equivalent:

  1. SELECT ... WHERE poly &> geom

overlaps_above

Availability: PostGIS, PGRaster (Conversion)

Tests if the geometry field’s bounding box overlaps or is above the lookup geometry’s bounding box.

举例:

  1. Zipcode.objects.filter(poly__overlaps_above=geom)

PostGIS equivalent:

  1. SELECT ... WHERE poly |&> geom

overlaps_below

Availability: PostGIS, PGRaster (Conversion)

Tests if the geometry field’s bounding box overlaps or is below the lookup geometry’s bounding box.

举例:

  1. Zipcode.objects.filter(poly__overlaps_below=geom)

PostGIS equivalent:

  1. SELECT ... WHERE poly &<| geom

strictly_above

Availability: PostGIS, PGRaster (Conversion)

Tests if the geometry field’s bounding box is strictly above the lookup geometry’s bounding box.

举例:

  1. Zipcode.objects.filter(poly__strictly_above=geom)

PostGIS equivalent:

  1. SELECT ... WHERE poly |>> geom

strictly_below

Availability: PostGIS, PGRaster (Conversion)

Tests if the geometry field’s bounding box is strictly below the lookup geometry’s bounding box.

举例:

  1. Zipcode.objects.filter(poly__strictly_below=geom)

PostGIS equivalent:

  1. SELECT ... WHERE poly <<| geom

距离查找

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

For an overview on performing distance queries, please refer to the distance queries introduction.

Distance lookups take the following form:

  1. <field>__<distance lookup>=(<geometry/raster>, <distance value>[, 'spheroid'])
  2. <field>__<distance lookup>=(<raster>, <band_index>, <distance value>[, 'spheroid'])
  3. <field>__<band_index>__<distance lookup>=(<raster>, <band_index>, <distance value>[, 'spheroid'])

The value passed into a distance lookup is a tuple; the first two values are mandatory, and are the geometry to calculate distances to, and a distance value (either a number in units of the field, a Distance object, or a query expression). To pass a band index to the lookup, use a 3-tuple where the second entry is the band index.

On every distance lookup except dwithin, an optional element, 'spheroid', may be included to use the more accurate spheroid distance calculation functions on fields with a geodetic coordinate system.

On PostgreSQL, the 'spheroid' option uses ST_DistanceSpheroid instead of ST_DistanceSphere. The simpler ST_Distance function is used with projected coordinate systems. Rasters are converted to geometries for spheroid based lookups.

distance_gt

Returns models where the distance to the geometry field from the lookup geometry is greater than the given distance value.

举例:

  1. Zipcode.objects.filter(poly__distance_gt=(geom, D(m=5)))
BackendSQL Equivalent
PostGISST_Distance/ST_Distance_Sphere(poly, geom) > 5
MariaDBST_Distance(poly, geom) > 5
MySQLST_Distance(poly, geom) > 5
OracleSDO_GEOM.SDO_DISTANCE(poly, geom, 0.05) > 5
SpatiaLiteDistance(poly, geom) > 5

distance_gte

Returns models where the distance to the geometry field from the lookup geometry is greater than or equal to the given distance value.

举例:

  1. Zipcode.objects.filter(poly__distance_gte=(geom, D(m=5)))
BackendSQL Equivalent
PostGISST_Distance/ST_Distance_Sphere(poly, geom) >= 5
MariaDBST_Distance(poly, geom) >= 5
MySQLST_Distance(poly, geom) >= 5
OracleSDO_GEOM.SDO_DISTANCE(poly, geom, 0.05) >= 5
SpatiaLiteDistance(poly, geom) >= 5

distance_lt

Returns models where the distance to the geometry field from the lookup geometry is less than the given distance value.

举例:

  1. Zipcode.objects.filter(poly__distance_lt=(geom, D(m=5)))
BackendSQL Equivalent
PostGISST_Distance/ST_Distance_Sphere(poly, geom) < 5
MariaDBST_Distance(poly, geom) < 5
MySQLST_Distance(poly, geom) < 5
OracleSDO_GEOM.SDO_DISTANCE(poly, geom, 0.05) < 5
SpatiaLiteDistance(poly, geom) < 5

distance_lte

Returns models where the distance to the geometry field from the lookup geometry is less than or equal to the given distance value.

举例:

  1. Zipcode.objects.filter(poly__distance_lte=(geom, D(m=5)))
BackendSQL Equivalent
PostGISST_Distance/ST_Distance_Sphere(poly, geom) <= 5
MariaDBST_Distance(poly, geom) <= 5
MySQLST_Distance(poly, geom) <= 5
OracleSDO_GEOM.SDO_DISTANCE(poly, geom, 0.05) <= 5
SpatiaLiteDistance(poly, geom) <= 5

dwithin

Returns models where the distance to the geometry field from the lookup geometry are within the given distance from one another. Note that you can only provide Distance objects if the targeted geometries are in a projected system. For geographic geometries, you should use units of the geometry field (e.g. degrees for WGS84) .

举例:

  1. Zipcode.objects.filter(poly__dwithin=(geom, D(m=5)))
BackendSQL Equivalent
PostGISST_DWithin(poly, geom, 5)
OracleSDO_WITHIN_DISTANCE(poly, geom, 5)
SpatiaLitePtDistWithin(poly, geom, 5)

聚合函数

Django provides some GIS-specific aggregate functions. For details on how to use these aggregate functions, see the topic guide on aggregation.

关键字参数描述
toleranceThis keyword is for Oracle only. It is for the tolerance value used by the SDOAGGRTYPE procedure; the Oracle documentation has more details.

举例:

  1. >>> from django.contrib.gis.db.models import Extent, Union
  2. >>> WorldBorder.objects.aggregate(Extent('mpoly'), Union('mpoly'))

Collect

class Collect(geo_field)

Availability: PostGIS, SpatiaLite

Returns a GEOMETRYCOLLECTION or a MULTI geometry object from the geometry column. This is analogous to a simplified version of the Union aggregate, except it can be several orders of magnitude faster than performing a union because it rolls up geometries into a collection or multi object, not caring about dissolving boundaries.

Extent

class Extent(geo_field)

Availability: PostGIS, Oracle, SpatiaLite

Returns the extent of all geo_field in the QuerySet as a four-tuple, comprising the lower left coordinate and the upper right coordinate.

举例:

  1. >>> qs = City.objects.filter(name__in=('Houston', 'Dallas')).aggregate(Extent('poly'))
  2. >>> print(qs['poly__extent'])
  3. (-96.8016128540039, 29.7633724212646, -95.3631439208984, 32.782058715820)

Extent3D

class Extent3D(geo_field)

Availability: PostGIS

Returns the 3D extent of all geo_field in the QuerySet as a six-tuple, comprising the lower left coordinate and upper right coordinate (each with x, y, and z coordinates).

举例:

  1. >>> qs = City.objects.filter(name__in=('Houston', 'Dallas')).aggregate(Extent3D('poly'))
  2. >>> print(qs['poly__extent3d'])
  3. (-96.8016128540039, 29.7633724212646, 0, -95.3631439208984, 32.782058715820, 0)

MakeLine

class MakeLine(geo_field)

Availability: PostGIS, SpatiaLite

Returns a LineString constructed from the point field geometries in the QuerySet. Currently, ordering the queryset has no effect.

举例:

  1. >>> qs = City.objects.filter(name__in=('Houston', 'Dallas')).aggregate(MakeLine('poly'))
  2. >>> print(qs['poly__makeline'])
  3. LINESTRING (-95.3631510000000020 29.7633739999999989, -96.8016109999999941 32.7820570000000018)

Union

class Union(geo_field)

Availability: PostGIS, Oracle, SpatiaLite

This method returns a GEOSGeometry object comprising the union of every geometry in the queryset. Please note that use of Union is processor intensive and may take a significant amount of time on large querysets.

备注

If the computation time for using this method is too expensive, consider using Collect instead.

举例:

  1. >>> u = Zipcode.objects.aggregate(Union(poly)) # This may take a long time.
  2. >>> u = Zipcode.objects.filter(poly__within=bbox).aggregate(Union(poly)) # A more sensible approach.

脚注

[1]See OpenGIS Simple Feature Specification For SQL, at Ch. 2.1.13.2, p. 2-13 (The Dimensionally Extended Nine-Intersection Model).
[2]See SDO_RELATE documentation, from the Oracle Spatial and Graph Developer’s Guide.
[3](1, 2) For an explanation of this routine, read Quirks of the “Contains” Spatial Predicate by Martin Davis (a PostGIS developer).