Django TastyPie Geo距离查找 [英] Django TastyPie Geo Distance Lookups

查看:133
本文介绍了Django TastyPie Geo距离查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用TastyPie进行地理距离查找。这有点困难,因为它不是由TastyPie支持。在Github上(https://gist.github.com/1067176)我发现了以下代码示例:

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)

效果很好,但现在我想把这个距离作为TastyPie的一个字段结果。你有什么想法吗?只需在fields属性中包含distance即可。

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.

提前感谢您的帮助!

推荐答案

元属性中定义的字段不足以返回附加值。
他们需要在资源中定义为额外的字段:

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)

可以通过定义 dehydrate_distance 资源中的方法

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本身附加一个名为resource_uri的字段,实际上并不存在于查询器中,查看tastypie资源的源代码可能是对您也有帮助。

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.

这篇关于Django TastyPie Geo距离查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆