使用tastypie从PointField返回纬度和经度值

时间:2012-09-06 13:26:58

标签: python django api tastypie geodjango

使用django-tastypie v0.9.11 django 1.4.1geodjango

在geodjango之前,我曾经将我的lat和lng值直接保存到我的模型中。然后,当我调用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"
},

现在我已将网络平台升级为使用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"
},

正如您所看到的,点值不同,因此我的移动应用程序正在崩溃。

我的问题是如何从点数字段中获取纬度和经度值,并像之前一样使用查询集返回它们?

1 个答案:

答案 0 :(得分:8)

您需要覆盖 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

相关问题