我正在使用TastyPie进行地理距离查找。这有点困难,因为TastyPie通常不支持它。在Github (https://gist.github.com/1067176)上,我找到了以下代码示例:
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中将距离作为字段结果。你知道怎么做吗?仅仅在field属性中包含"distance“是行不通的。
提前感谢您的帮助!
发布于 2012-09-05 19:35:51
meta属性中定义的字段不足以返回附加值。它们需要定义为资源中的附加字段:
distance = fields.CharField(attribute="distance", default=0, readonly=True)可以通过在资源内定义dehydrate_distance方法来填充此值
def dehydrate_distance(self, bundle):
# your code here或者在资源元中的queryset中添加一些额外的元素,如下所示:
queryset = YourModel.objects.extra(select={'distance': 'SELECT foo FROM bar'})Tastypie本身附加了一个名为resource_uri的字段,这个字段实际上并不存在于查询集中,查看一下tastypie资源的源代码可能也会对您有所帮助。
https://stackoverflow.com/questions/12279221
复制相似问题