3

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!

Matthias Scholz
  • 1,015
  • 1
  • 13
  • 25

1 Answers1

4

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.

Ania Warzecha
  • 1,796
  • 13
  • 26
  • 1
    That works! Thanks so much for that, it's exactly what I wanted! The value is actually be filled in by the .distance() geodjango function, so I just had to add that field definition. Once again, thanks! – Matthias Scholz Sep 05 '12 at 12:15