问题
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!
回答1:
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.
来源:https://stackoverflow.com/questions/12279221/django-tastypie-geo-distance-lookups