GeoDjango Querying Points Within Distance

November 25, 2011

I wanted to produce a list of bands that are near an origin point, ordered by distance. See for details of my model.

Here's the view code used. This selects an origin point (the band with id 1) and then selects all bands that are within 10 miles of this point.

from django.contrib.gis.measure import D

lOrigin = Band.objects.filter(id=1)[0]
lNearestBands = Band.objects.filter(point__distance_lte=(lOrigin.point, D(mi=10))).distance(lOrigin.point).exclude(

We then sort the list of bands by distance:

lBandsList = []
for band in lNearestBands:
    lBandsList.append((band.distance, band))

As we pass this array of tuples to the view as NearestBands.

In the template we iterate this tuple printing the band name and distance.

{% for distance, eachband in NearestBands %}
  <li>{{}} - {{distance.mi|floatformat}} miles</li>
{% endfor %}

As the distance atribute decorated onto the band is a Distance object (see you can add the units you want on the end (in this example I've used mi for miles) and it will convert for you.

See also