2012-09-05 40 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函數填充,所以我只需添加該字段定義。再一次,謝謝! –