Reputation: 693
Using Tastypie and GeoDjango, I'm trying to return results of buildings located within 1 mile of a point.
The TastyPie documentation states that distance lookups are not yet supported, but I am finding examples of people getting it work, such as this discussion and this discussion on StackOverflow, but no working code examples that can be applied.
The idea that I am trying to work with is if I append a GET command to the end of a URL, then nearby locations are returned, for example:
http://website.com/api/?format=json&building_point__distance_lte=[{"type": "Point", "coordinates": [153.09537, -27.52618]},{"type": "D", "m" : 1}]
But when I try that, all I get back is:
{"error": "Invalid resource lookup data provided (mismatched type)."}
I've been pouring over the Tastypie document for days now and just can't figure out how to implement this.
I'd provide more examples, but I know they'd be all terrible. All advice is appreciated, thank you!
Upvotes: 3
Views: 187
Reputation: 693
Got it working, here is an example for posterity:
In the api.py, create a Resource that looks like this:
from django.contrib.gis.geos import *
class LocationResource(ModelResource):
class Meta:
queryset = Building.objects.all()
resource_name = 'location'
def apply_sorting(self, objects, options=None):
if options and "longitude" in options and "latitude" in options:
pnt = fromstr("POINT(" + options['latitude'] + " " + options['longitude'] + ")", srid=4326)
return objects.filter(building_point__distance_lte=(pnt, 500))
return super(LocationResource, self).apply_sorting(objects, options)
The "building" field is defined as a PointField in models.py.
Then in the URL for the resource, append the following, for example:
&latitude=-88.1905699999999939&longitude=40.0913469999999990
This will return all objects within 500 meters.
Upvotes: 2