使用 django-tastypie v0.9.11 django 1.4.1和 geodjango .
在使用 geodjango 之前,我曾经将我的纬度和经度值直接保存到我的模型中。然后,当我调用 API 时,我会很容易地提取我的值。像这样:
{
"id": "1",
"lat": "-26.0308215267084719",
"lng": "28.0101370772476450",
"author": "\/api\/v1\/user\/3\/",
"created_on": "2012-07-18T14:33:31.081105",
"name": "qweqwe",
"updated_on": "2012-09-06T14:17:01.658947",
"resource_uri": "\/api\/v1\/spot\/1\/",
"slug": "qweqwe"
},
现在我已经升级我的 webapp 以使用 geodjango我现在将我的信息存储在 PointField() 中.现在,如果我对 API 进行与过去相同的调用,我将返回:
{
"id": "1",
"point": "POINT (28.0101370772476450 -26.0308215267084719)",
"author": "\/api\/v1\/user\/3\/",
"created_on": "2012-07-18T14:33:31.081105",
"name": "qweqwe",
"updated_on": "2012-09-06T14:17:01.658947",
"resource_uri": "\/api\/v1\/spot\/1\/",
"slug": "qweqwe"
},
如您所见,点值不同,因此我的移动应用程序出现故障。
我的问题是如何从点字段中获取纬度和经度值并像以前一样通过查询集返回它们?
最佳答案
您需要重写您的dehydrate() 方法,如http://django-tastypie.readthedocs.org/en/latest/cookbook.html#adding-custom-values 中所述
所以这样的事情可能对你有用:
class MyModelResource(Resource):
class Meta:
qs = MyModel.objects.all()
def dehydrate(self, bundle):
# remove unneeded point-field from the response data
del bundle.data['point']
# add required fields back to the response data in the form we need it
bundle.data['lat'] = bundle.obj.point.y
bundle.data['lng'] = bundle.obj.point.x
return bundle
顺便说一下,tastypie 的开发版不久前就支持了 geodjango,您可能会感兴趣,可以去看看。这些文档位于 http://django-tastypie.readthedocs.org/en/latest/geodjango.html。
关于python - 使用 tastypie 从 PointField 返回纬度和经度值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12301195/