Programming Language: Python

Namespace/Package Name: django.contrib.gis.db.models.functions

Class/Type: Distance

Examples at hotexamples.com: 30

The `Distance` function is part of the `django.contrib.gis.db.models.functions` module, which provides GIS-related database functions for use with Django's ORM.

The `Distance` function calculates the distance between two points on a GIS-enabled database, based on the spatial reference system (SRS) used.

Here are some examples of how to use `Distance` in Django:

**Example 1:** Calculate the distance between two points on a map

**Example 2:** Query all locations within a certain radius of a given point

The `Distance` function calculates the distance between two points on a GIS-enabled database, based on the spatial reference system (SRS) used.

Here are some examples of how to use `Distance` in Django:

from django.contrib.gis.db.models.functions import Distance from myapp.models import Location # Assume we have a Location model with `point` field representing a point on the map origin_point = Location.objects.get(name='New York') destination_point = Location.objects.get(name='Los Angeles') # Calculate the distance between the two points in miles distance = origin_point.point.distance(destination_point.point).miles # Alternatively, use the `Distance` function to calculate the distance distance = Location.objects.annotate( distance=Distance('point', destination_point.point) ).get(id=origin_point.id).distance.miles

from django.contrib.gis.db.models.functions import Distance from django.contrib.gis.geos import Point from myapp.models import Location # Assume we have a Location model with a `point` field representing a point on the map # and a `name` field representing the name of the location search_point = Point(-122.4194, 37.7749) # San Francisco # Filter locations within a 10 mile radius of `search_point` locations_within_radius = Location.objects.annotate( distance=Distance('point', search_point) ).filter(distance__lte=10) for loc in locations_within_radius: print(f"{loc.name} is {loc.distance.mi} miles away from San Francisco")Package/library: `django.contrib.gis`

Frequently Used Methods