2012-09-05 45 views
3

我使用TastyPie进行地理距离查找。这有点困难,因为它不被TastyPie支持。在GitHub上(https://gist.github.com/1067176)我发现下面的代码示例:Django TastyPie Geo距离查找

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。你有什么想法如何做到这一点?只在字段属性中包含“距离”不起作用。

在此先感谢您的帮助!

回答

4

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

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

此值可以通过定义资源

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

内部dehydrate_distance方法或通过加入一些额外的元件被填充到在资源元查询集像这样:

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

Tastypie本身附加一个名为resource_uri的字段,该字段实际上并不存在于该队列中ryset,查看tastypie资源的源代码也可能对您有所帮助。

+1

工作!非常感谢,这正是我想要的!该值实际上由.distance()geodjango函数填充,所以我只需添加该字段定义。再一次,谢谢! –