Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django TastyPie Geo Distance Lookups

I'm using TastyPie for Geo-distance lookups. That is a bit difficult, because oficially its not supported by TastyPie. On Github (https://gist.github.com/1067176) I found the following code-sample:

 def apply_sorting(self, objects, options=None):
     if options and "longitude" in options and "latitude" in options:
         return objects.distance(Point(float(options['latitude']), float(options['longitude']))).order_by('distance')

     return super(UserLocationResource, self).apply_sorting(objects, options)

It works well, but now I would like to have the distance as a field result in TastyPie. Do you have any idea how to do that? Just including "distance" in the fields attribute doesn't work.

Thanks in advance for your help!

like image 725
Matthias Scholz Avatar asked Dec 07 '25 02:12

Matthias Scholz


1 Answers

The fields defined in the meta attributes aren't enough to have the additional values returned. They need to be defined as additional fields in the resource:

distance = fields.CharField(attribute="distance", default=0, readonly=True)

This value can be filled by defining dehydrate_distance method inside the resource

def dehydrate_distance(self, bundle):
    # your code here

or by adding some additional elements to queryset in resources meta like so:

queryset = YourModel.objects.extra(select={'distance': 'SELECT foo FROM bar'})

Tastypie itself appends a field called resource_uri that isn't actually present in the queryset, looking at the source code of tastypie's resources might be helpful for you too.

like image 148
Ania Warzecha Avatar answered Dec 08 '25 16:12

Ania Warzecha