class Distance(expr1, expr2, spheroid=None, **extra)
Availability: MySQL (≥ 5.6.1), PostGIS, Oracle, SpatiaLite
Accepts two geographic fields or expressions and returns the distance between them, as a Distance
object. On MySQL, a raw float value is returned, as it’s not possible to automatically determine the unit of the field.
On backends that support distance calculation on geodetic coordinates, the proper backend function is automatically chosen depending on the SRID value of the geometries (e.g. ST_Distance_Sphere
on PostGIS).
When distances are calculated with geodetic (angular) coordinates, as is the case with the default WGS84 (4326) SRID, you can set the spheroid
keyword argument to decide if the calculation should be based on a simple sphere (less accurate, less resource-intensive) or on a spheroid (more accurate, more resource-intensive).
In the following example, the distance from the city of Hobart to every other PointField
in the AustraliaCity
queryset is calculated:
>>> from django.contrib.gis.db.models.functions import Distance >>> pnt = AustraliaCity.objects.get(name='Hobart').point >>> for city in AustraliaCity.objects.annotate(distance=Distance('point', pnt)): ... print(city.name, city.distance) Wollongong 990071.220408 m Shellharbour 972804.613941 m Thirroul 1002334.36351 m ...
Note
Because the distance
attribute is a Distance
object, you can easily express the value in the units of your choice. For example, city.distance.mi
is the distance value in miles and city.distance.km
is the distance value in kilometers. See Measurement Objects for usage details and the list of Supported units.
Please login to continue.