[GIS] GeoDjango: Find all points within radius

geodjangopostgis

I am working in GeoDjango (with a Django 1.7 and PostGIS 2.1.4 backend). I have a model with a PointField in my database and I am trying to find all items within 10km radius of a point.

Here is my model code:

class Place(models.Model):
    id = models.IntegerField(primary_key=True)
    location = models.PointField(null=True, blank=True)
    objects = models.GeoManager()

Here is my view code (abridged for readability):

    from django.contrib.gis.geos import Point
    from django.contrib.gis.measure import Distance
    lat = 52.5
    lng = 1.0
    radius = 10
    point = Point(lng, lat)
    print point
    places = Place.objects.filter(location__dwithin=(point.location, Distance(km=radius)))

This gives me:

AttributeError: 'Point' object has no attribute 'location'

I see the point in the console: POINT (1.0000000000000000 52.5000000000000000).

How should I structure the query differently?

If I try just using point rather than point.location (as per the dwithin documentation) then I get a different error: ValueError: Only numeric values of degree units are allowed on geographic DWithin queries.

UPDATE:

This seems to work, but I don't know if it's correct:

    radius = int(radius)
    degrees = radius / 111.325
    point = Point(float(lng), float(lat))
    places = Place.objects.filter(location__dwithin=(point, degrees))

The results look OK, but I don't know if my conversion to degrees is reasonable.

Best Answer

from django.contrib.gis.geos import Point
from django.contrib.gis.measure import Distance  


lat = 52.5
lng = 1.0
radius = 10
point = Point(lng, lat)    
Place.objects.filter(location__distance_lt=(point, Distance(km=radius)))