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 http://drumcoder.co.uk/blog/2011/nov/18/adding-geodjango-existing-project/ 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(id=lOrigin.id)

We then sort the list of bands by distance:

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

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.

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

As the distance atribute decorated onto the band is a Distance object (see https://docs.djangoproject.com/en/dev/ref/contrib/gis/measure/#django.contrib.gis.measure.Distance) 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