Skip to content

Instantly share code, notes, and snippets.

@bohde
Created July 6, 2011 13:07
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save bohde/1067176 to your computer and use it in GitHub Desktop.
Save bohde/1067176 to your computer and use it in GitHub Desktop.
Tastypie support for Geodjango distance filtering
class MyGeoResource(Resource):
def apply_sorting(self, objects, options=None):
if options and "longitude" in options and "latitude" in options:
return objects.distance(Point(options['latitude'], options['longitude'])).order_by('distance')
return super(MyGeoResource, self).apply_sorting(objects, options)
curl localhost:8000/api/v1/mygeoresource?latitude=<>&longitude=<>&limit=1
@panchicore
Copy link

thanks for this snipped, I have some questions:

  • how do I apply it to a ModelResource?
  • why your MyGeoResource does not contains the Meta class that declare what queryset you will use?
  • can you provide a source where it is fully implemented?

thanks in advance!

@bohde
Copy link
Author

bohde commented Sep 12, 2011

This was just an example snippet to help someone else, and wasn't actually fully implemented by me. However, it should probably work with a standard ModelResource with a GeoDjango model/queryset.

@panchicore
Copy link

thanks for your quick answer.

Yes, works with a standar ModelResource, but the the "coords" fields need to be named different as you send it in the GET params "latitude" and "longitude", my Location class have: latitude and longitude, so, testypie try to make a filtering related with this fields. if I send by GET params "lat" and "lng" then I can use the original object_list in apply_sorting method. thanks again.

@Morpho
Copy link

Morpho commented Sep 5, 2012

Hi, great example! Do you have any idea how to include the distance in tastypie's fields? Just including it like fields = [... 'distance'] doesnt work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment